package com.bbcare.followup.plat.service.impl;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.service.IBsSmsTemplateService;
import com.bbcare.department.plat.store.ibatis.IDeparmentBasicDao;
import com.bbcare.followup.plat.entity.ContentTemplVersion;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PatientContentData;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.entity.PatientTaskContent;
import com.bbcare.followup.plat.entity.PtEvaluationGuide;
import com.bbcare.followup.plat.entity.PtEvaluationOrder;
import com.bbcare.followup.plat.entity.PtEvaluationResult;
import com.bbcare.followup.plat.entity.PtSmsRd;
import com.bbcare.followup.plat.entity.PtUserextendInfo;
import com.bbcare.followup.plat.service.IFollowEvaluationScoreService;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.service.IPatientqueryCardService;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.followup.plat.store.ibatis.IContentTemplDAO;
import com.bbcare.followup.plat.store.ibatis.IEvaluationWorkOrderDAO;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientExtendDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientOperationRecordDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskContentDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientTaskDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientqueryCardDAO;
import com.bbcare.followup.plat.store.ibatis.IPtSmsRdDao;
import com.bbcare.plat.support.service.IBizInterAsClient;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

/*
 * @name:         查询用户服务类实现
 * @createTime:   2017.5.16
 * @description:  患者相关操作等
 * @modify:
 * @author:        wuyz
 */
@Service
public class PatientqueryCardService implements IPatientqueryCardService {
	private final Log logger = LogFactory.getLog(PatientqueryCardService.class);

	@Autowired
	private IPatientqueryCardDAO patientqueryCardDAO;

	@Autowired
	private IPtSmsRdDao IPtSmsRdDao;

	@Autowired
	private IPatientDAO patientDao;

	@Autowired
	private IPatientQueueSchemeDAO patientQueueSchemeDao;

	@Autowired
	private IPatientService patientSerivce;

	@Autowired
	private IPatientTaskContentDAO patientTaskConDao;

	@Autowired
	private IPatientTaskDAO patientTaskDao;

	@Autowired
	private AppPatientAotuService AppPatientAotuService;

	@Autowired
	private IBizInterAsClient bizInterClient;

	@Autowired
	private IPatientInfoHisService patientInfoHisService;

	@Autowired
	private IPatientOperationRecordDAO patientOperationRecordDao;

	@Autowired
	private IDeparmentBasicDao departBasicDao;

	@Autowired
	private IFollowQueueDAO queueDao;

	@Autowired
	private IContentTemplDAO contentTemplDao;

	@Autowired
	private PatientInfoHisService PatientInfoHisService;

	@Autowired
	private IConfCacheDAO IConfCacheDAO;

	@Autowired
	private IBsSmsTemplateService bsSmsTemplateService;

	@Autowired
	private IDeparmentBasicDao deparmentBasicDao;

	@Autowired
	private IPatientExtendDAO ptExtendDao;

	@Autowired
	private FamilyReportService familyReportService;

	@Autowired
	private IFollowEvaluationScoreService followEvaluationScoreService;

	@Autowired
	private IFollowEvaluationService followEvaluationService;

	@Autowired
	private IEvaluationWorkOrderDAO evaluationWorkOrderDAO;

	@Autowired
	private IFollowQueueService followQueueSerivce;

	@Autowired
	PatientService patientService;

	@Resource(name = "jedisPool")
	private JedisPool jedisPool;

	@SuppressWarnings("unchecked")
	@Override
	public ResultModel<HashMap<String, Object>> querypatientid(Map<String, Object> paramMap) throws Exception {
		HashMap<String, Object> userMap = new HashMap<String, Object>(paramMap);
		logger.info("进入通过微信id查询患者id#######12wwww######begin" + paramMap.toString());
		// 查询当前微信是否绑定了号码
		List<Map<String, Object>> wechatList = IConfCacheDAO.selectwechat(paramMap);
		if (wechatList != null && wechatList.size() > 0) {
			userMap.put("bindPhoneNo", String.valueOf(wechatList.get(0).get("phone_no")));
		} else {
			userMap.put("bindPhoneNo", "");
		}

		paramMap.remove("openId");
		logger.info(" paramMap最后的入参：" + paramMap.toString());
		List<Map<String, Object>> list = patientqueryCardDAO.selectpatientid(paramMap);

		String newCard = "";
		logger.info("out selectpatientid" + list.toString());
		String dateNow = DateUtil.getDateHm();// 获取当前时间 yyyy-mm-dd hh:mm
		if (list.size() <= 0 || StringUtils.isEmpty(list)) {
			userMap.put("flag", "2");
			userMap.put("userFlag", "2");
			userMap.put("newCard", "");
			return new ResultModel<HashMap<String, Object>>(userMap);
		} else {
			userMap.put("userFlag", "1");
			paramMap.put("id", list.get(0).get("id"));
			Map<String, Object> mapOne = new HashMap<String, Object>();
			logger.info("paramMap  : " + paramMap.toString());
			List<Map<String, Object>> listTwo = patientqueryCardDAO.selectcardId(paramMap);
			logger.info("sssssssssssss" + listTwo.toString());
			mapOne = list.get(0);
			if (listTwo.size() > 0 && listTwo != null) {
				mapOne.put("scheme_id", listTwo.get(0).get("scheme_id"));
				String dateOrder = "";
				int bigOne = -1;
				if (StringUtils.isEmpty(listTwo.get(0).get("date"))) {
				} else {
					dateOrder = listTwo.get(0).get("date").toString();
					bigOne = dateOrder.compareTo(dateNow);
				}
				logger.info("bigOne:" + bigOne);
				if (bigOne > 0 && !StringUtils.isEmpty(listTwo.get(0).get("reservation_id"))) {
					mapOne.put("status", "Y");
				} else {
					mapOne.put("status", "N");
				}
				userMap.put("userInfo", mapOne);
			} else {
				mapOne.put("status", "N");
				userMap.put("userInfo", mapOne);
			}
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> servParamMap = new LinkedHashMap<String, Object>();
				Map<String, Object> map = new HashMap<String, Object>();
				map = list.get(i);
				servParamMap.put("code", Constants.STRING_SERVICECODE_A09U003O);
				servParamMap.put("patName", map.get("user_name"));
				servParamMap.put("pattel", map.get("phone_no"));
				servParamMap.put("platform_code", Constants.SOURCE_TPLATFORM_CODE);
				servParamMap.put("platform_key", map.get("id"));
				servParamMap.put("pathash", "");
				servParamMap.put("bookeddept", userMap.get("bookeddept"));
				servParamMap.put("is_bind", "no");
				servParamMap.put("cardno", "");
				logger.info("servParamMap111111111111" + servParamMap.toString());
				String argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", servParamMap);
				logger.info("argmsg   :  " + argmsg);
				// String argmsg="";

				/*
				 * argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?>"+ "<rows>"+
				 * "<row result=\"1\" message=\"查询成功\" cardno=\"133**0001\" pathash=\"\" is_bind=\"no\" />"
				 * + "</rows>";
				 */

				/*
				 * argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?>"+ "<rows>"+
				 * "<row result=\"1\" message=\"查询成功\" cardno=\"188**0001\" pathash=\"\" is_bind=\"no\" />"
				 * + "</rows>";
				 */

				// argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?><rows></rows>" ;

				List<Map<String, Object>> listone = ToolUtils.FormatXml(argmsg);
				logger.info("listone:出参：" + listone.toString());
				if (listone != null && listone.size() > 0 && !StringUtils.isEmpty(listone.get(0).get("cardno"))) {
					servParamMap.put("cardno", listone.get(0).get("cardno"));
					newCard = listone.get(0).get("cardno").toString();
				} else {
					Map<String, Object> ptExtMap = new HashMap<String, Object>();
					ptExtMap.put("paramName", Constants.SERVICE_NAME_FOR_EXTEND);
					ptExtMap.put("userId", map.get("id"));
					ptExtMap.put("queueId", (String) paramMap.get("queueId"));
					List<PtUserextendInfo> ptextList = ptExtendDao.selectPtExtendInfo(ptExtMap);
					if (!CollectionUtils.isEmpty(ptextList)) {
						servParamMap.put("code", Constants.STRING_SERVICECODE_A09U003O);
						servParamMap.put("pattel", ptextList.get(0).getParamValue());
						servParamMap.put("bookeddept", userMap.get("bookeddept"));
						logger.info("servParamMap备用手机号:" + servParamMap.toString());
						argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", servParamMap);

						/*
						 * argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?>"+ "<rows>"+
						 * "<row result=\"1\" message=\"查询成功\" cardno=\"133**0001\" pathash=\"\" is_bind=\"no\" />"
						 * + "</rows>";
						 */

						listone = ToolUtils.FormatXml(argmsg);
						if (listone != null && listone.size() > 0
								&& !StringUtils.isEmpty(listone.get(0).get("cardno"))) {
							logger.info(map.get("id") + "==通过备用手机号，查询到用户预约信息");
							servParamMap.put("cardno", listone.get(0).get("cardno"));
							newCard = listone.get(0).get("cardno").toString();
						}
					}
				}
				servParamMap.put("id", map.get("id"));
				servParamMap.put("queueId", paramMap.get("queueId"));
				/*
				 * String bind = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "",
				 * servParamMap); List<Map<String, Object>> listTow= ToolUtils.FormatXml(bind);
				 * if(!StringUtils.isEmpty(listTow.get(0).get("pathash"))){ userMap.put("flag",
				 * "1"); userMap.put("userInfo", map); userMap.put("cardMessage", listTow); }
				 */
				List<Map<String, Object>> lists = patientqueryCardDAO.selectcardId(servParamMap);
				if (lists != null && !lists.isEmpty() && !StringUtils.isEmpty(lists.get(0).get("card_no"))) {
					userMap.put("flag", "1");
					map.put("scheme_id", lists.get(0).get("scheme_id"));
					String dateOrder = "";
					int bigOne = -1;
					if (StringUtils.isEmpty(lists.get(0).get("date"))) {
					} else {
						dateOrder = lists.get(0).get("date").toString();
						bigOne = dateOrder.compareTo(dateNow);
					}
					logger.info("bigOne有:" + bigOne);
					if (bigOne > 0 && !StringUtils.isEmpty(lists.get(0).get("reservation_id"))) {
						map.put("status", "Y");
					} else {
						map.put("status", "N");
					}
					userMap.put("userInfo", map);
					userMap.put("cardMessage", lists.get(0));
				}
			}
		}
		if ("".equals(userMap.get("cardMessage")) || null == userMap.get("cardMessage")) {
			userMap.put("flag", "2");
		}
		// 是否挂号
		if (!StringUtils.isEmpty(newCard)) {
			userMap.put("newCard", newCard);
			Map<String, Object> mapinfo = new HashMap<String, Object>();
			mapinfo = (Map<String, Object>) userMap.get("userInfo");
			mapinfo.put("status", "Y");
			userMap.put("userInfo", mapinfo);
		} else {
			userMap.put("newCard", "");
		}
		return new ResultModel<HashMap<String, Object>>(userMap);
	}

	@Override
	public List<Map<String, Object>> querycardId(Map<String, Object> paramMap) throws Exception {
		logger.info("进入通过患者id查询用户绑定卡信息#############begin");
		List<Map<String, Object>> list = patientqueryCardDAO.selectcardId(paramMap);
		// logger.info("list2222222222222"+list.toString());
		logger.info("out selectpatientid");
		return list;
	}

	@Override
	@Transactional
	public ResultModel<HashMap<String, Object>> addsendPromptSms_tx(String phoneNo, String smsType, String smsContent)
			throws Exception {
		HashMap<String, Object> paraMap = new HashMap<String, Object>();
		Map<String, Object> mapIn = new HashMap<String, Object>();
		paraMap = this.addsendPromptSmsImpl(phoneNo, smsType, smsContent, mapIn);
		return new ResultModel<HashMap<String, Object>>(paraMap);
	}

	/*
	 * 短信发送具体实现方法
	 */
	@Override
	@SuppressWarnings("deprecation")
	public HashMap<String, Object> addsendPromptSmsImpl(String phoneNo, String smsType, String smsContent,
			Map<String, Object> mapIn) throws Exception {
		HashMap<String, Object> paraMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("phoneNo", phoneNo);
		map.put("smsType", smsType);
		// 每天同一个号码，同种类型的短信最多10条
		if (smsType.equals("01") || smsType.equals("02") || smsType.equals("04") || smsType.equals("07")) {
			int smsCount = IPtSmsRdDao.querySmsCountByNowDayMpSmsType(map);
			logger.info("smsCount : " + smsCount);
			if (smsCount > 0 && smsCount < 3) {
				List<Map<String, Object>> smsList = IPtSmsRdDao.getLastSms(map);
				if (smsList != null && smsList.size() > 0) {
					Timestamp sendTime = (Timestamp) smsList.get(0).get("create_time");
					throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
							"验证码已发送，请勿多次获取(验证码发送时间：" + sendTime.getHours() + "点" + sendTime.getMinutes() + "分左右)");
				}
			} else if (smsCount >= 3) {
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"尊敬的用户！您今天的短信次数已达到最大值，请明天操作！");
			}
		}
		String smsText = ""; // 短信验证码前半部分文字
		boolean flag = false;

		if ("03".equals(smsType)) {
			smsText = smsContent;
		} else if ("05".equals(smsType)) {
			smsText = smsContent;
		} else if ("06".equals(smsType)) { // 营销
			smsText = smsContent;
		}

		// 发送短信
		flag = this.addsendVerifySms_tx(phoneNo, smsType, smsText, mapIn);
		// 判断发送是否成功
		// 判断发送是否成功
		if (flag) {
			logger.info("进入通过患者flag" + flag);
			paraMap.put("flag", flag);
			paraMap.put("msg", "短信已发送!");
		} else {
			paraMap.put("flag", flag);
			paraMap.put("msg", "短信发送失败!");
		}

		return paraMap;
	}

	/**
	 * 发送验证码处理类
	 *
	 * @throws Exception
	 *
	 */
	public boolean addsendVerifySms_tx(String phoneNo, String smsType, String smsText, Map<String, Object> mapIn)
			throws Exception {
		// 生成验证码
		String verifyCode = "";
		if (smsType.equals("03") || smsType.equals("05") || smsType.equals("06")) {
			verifyCode = "";
		} else {
			verifyCode = ToolUtils.getRandom(4);
			smsText = verifyCode;
		}

		return this.add(phoneNo, smsText, smsType, verifyCode, mapIn);
	}

	/**
	 * 验证类短信发送
	 *
	 * @throws Exception
	 */
	private boolean add(String phoneNo, String msg, String smsType, String verifyCode, Map<String, Object> mapIn)
			throws Exception {
		String updateTime = "";
		String updateAccept = "";
		String authorId = "";
		String ptSchemeid = "";
		String queueId = "";
		String taskId = "";
		String userId = "";
		String ruleType = "";
		String taskName = "";
		String informType = "2";
		if (!MapUtils.isEmpty(mapIn)) {
			updateTime = (String) mapIn.get("updateTime");
			updateAccept = (String) mapIn.get("updateAccept");
			authorId = (String) mapIn.get("authorId");
			ptSchemeid = (String) mapIn.get("ptSchemeid");
			queueId = (String) mapIn.get("queueId");
			taskId = (String) mapIn.get("taskId");
			userId = (String) mapIn.get("userId");
			ruleType = (String) mapIn.get("ruleType");
			taskName = (String) mapIn.get("taskName");
			informType = (String) mapIn.get("informType");
		}

		boolean flag = false;
		Map<String, Object> paraMap = new HashMap<String, Object>();
		// 重新发送注册验证短信时将原短信设置为失效
		if (StringUtils.isEmpty(updateTime)) {
			updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
		}
		if (StringUtils.isEmpty(updateAccept)) {
			updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		}
		// 发送主机ip
		String ipAddress = "";
		try {
			InetAddress netAddress = InetAddress.getLocalHost();
			ipAddress = netAddress.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			ipAddress = "";
		}
		// 保存短信记录表
		// msg = "【贝生医疗】您的短信验证码为" + msg + "有效期5分钟";
		paraMap.put("phoneNo", phoneNo); // 手机号
		paraMap.put("smsText", msg); // 短信内容
		paraMap.put("smsType", smsType); // 短信类型:01-注册验证类短信;02-找回登陆密码;
		paraMap.put("verifyCode", verifyCode); // 验证码
		paraMap.put("verifyStatus", "00"); // 验证状态:00-默认状态;01-待验证;02-已验证;03-失效;
		paraMap.put("checkStatus", "01");// 状态:01-待发送;02-发送完成;03-发送失败;
		String ptSmsId = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PT_SMS_RD_ID);
		PtSmsRd psrVo = new PtSmsRd();
		psrVo.setCheckStatus("01");
		psrVo.setCreateAuthor(authorId);
		psrVo.setCreateTime(updateTime);
		psrVo.setId(ptSmsId);
		psrVo.setPhoneNo(phoneNo);
		psrVo.setPtSchemeid(ptSchemeid);
		psrVo.setQueueId(queueId);
		psrVo.setSendIp(ipAddress);
		psrVo.setSmsText(msg);
		psrVo.setSmsType(smsType);
		psrVo.setTaskId(taskId);
		psrVo.setUpdateAccept(updateAccept);
		psrVo.setUserId(userId);
		psrVo.setVerifyCode(verifyCode);
		psrVo.setVerifyStatus("00");
		psrVo.setInformType(ruleType);
		psrVo.setTaskName(taskName);
		psrVo.setSendStatus("");
		psrVo.setInformType(informType);
		logger.info("paraMap :" + paraMap.toString());
		IPtSmsRdDao.failureUserRegSms(psrVo);
		IPtSmsRdDao.savePtSmsRd(psrVo);

		// 调用接口发送短信
		if (smsType.equals("01") || smsType.equals("02") || smsType.equals("04") || smsType.equals("07")) {
			flag = ToolUtils.sendALISmsNew(phoneNo, psrVo.getSmsText(), smsType);
		}
		if (smsType.equals("03")) {
			paraMap.put("ptSmsId", ptSmsId);
			int re = ToolUtils.sendYMsms(phoneNo, psrVo.getSmsText());
			if (re == 0) {
				flag = true;
			}
		}
		if (smsType.equals("05")) {
			paraMap.put("ptSmsId", ptSmsId);
			int re = ToolUtils.sendYMsms2(phoneNo, psrVo.getSmsText());
			logger.info("ToolUtils.sendYMsms2==re==" + re);
			if (re == 0) {
				flag = true;
			}
		}
		if (smsType.equals("06")) {
			paraMap.put("ptSmsId", ptSmsId);
			int re = ToolUtils.sendYMsms3(phoneNo, psrVo.getSmsText());
			if (re == 0) {
				flag = true;
			}
		}
		if (flag) {
			paraMap.put("verifyStatus", "01");
			paraMap.put("checkStatus", "02");
			paraMap.put("Status", "01");
			paraMap.put("sendStatus", Constants.PT_INFORM_SMS_STATUS_SUCCESS);
			IPtSmsRdDao.sendSuccRegSms(paraMap);
		} else {
			paraMap.put("checkStatus", "03");
			paraMap.put("Status", "01");
			paraMap.put("sendStatus", Constants.PT_INFORM_SMS_STATUS_FAILED);
			IPtSmsRdDao.sendFailSms(paraMap);
		}

		return flag;
	}

	// 获取当前时间
	public String getNow() {
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String CurrDate = dateFormat.format(now);
		return CurrDate;
	}

	@Override
	@Transactional
	public int checkVerifyCode(String phoneNo, String verifyCode, String smsType, String type, String wechat_id)
			throws Exception {
		int flag = 1;
		String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("wechat_id", wechat_id);
		map.put("phoneNo", phoneNo);
		List<Map<String, Object>> list = null;
		if (!StringUtils.isEmpty(wechat_id) && !"null".equals(wechat_id)) {
			list = IConfCacheDAO.selectwechat(map);
		}
		map.put("verifyCode", verifyCode);
		map.put("smsType", smsType);
		map.put("minute", 10);
		if (type.equals("1")) {
			// 对验证码验证
			logger.info("sssssssss: " + map.toString());
			List<Map<String, Object>> lists = IPtSmsRdDao.selectVerifyCode(map);
			if (lists.size() > 0 || verifyCode.equals("5533")) {
				if(verifyCode.equals("5533")){
					map.remove("verifyCode");
				}
				flag = 0;
				// 将短信验证码置为已校验
				map.put("verifyStatus", "02");
				IPtSmsRdDao.updateSms(map);
				if (list == null || list.size() <= 0) {
					if (!StringUtils.isEmpty(wechat_id) && !"null".equals(wechat_id)) {
						map.put("id", updateAccept);
						map.put("createTime", currTime);
						map.put("remark", "手机微信绑定");
						map.put("bak1", "");
						map.put("bak2", "");
						map.put("bak3", "");
						IConfCacheDAO.savwechatInfo(map);
					}
				} else {
					IConfCacheDAO.updatewechat(map);
				}
				return flag;
			} else {
				// 将短信验证码置为已校验
				map.remove("verifyCode");
				List<Map<String, Object>> listone = IPtSmsRdDao.selectVerifyCode(map);
				if (listone != null && listone.size() > 0) {
					String verify_code = listone.get(0).get("verify_code").toString();
					Jedis jedis = null;
					try {
						jedis = jedisPool.getResource();
						String code = jedis.get(verify_code);
						int inter = 0;
						if (code == null) {
							jedis.set(verify_code, "1");
						} else {
							inter = Integer.parseInt(code);
						}
						logger.info("inter~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + inter);
						if (inter == 5) {
							jedis.del(verify_code);
							map.put("minute", 1440);
							map.put("verifyStatus", "03");
							IPtSmsRdDao.updateSms(map);
							logger.info("111111111" + map.toString());
							return flag;
						} else {
							String str = inter + 1 + "";
							jedis.set(verify_code, str);
							throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
									"尊敬的用户，您的验证码输入错误，请核对!"));
						}

					} catch (JedisConnectionException jex) {
						logger.error("redis连接异常..." + jex.getMessage());
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
					} finally {
						if (null != jedis) {
							try {
								jedis.close();
								logger.warn("close redis connection...");
							} catch (Exception ex) {
								ex.printStackTrace();
								throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
										"Redis缓存关闭失败!"));
							}
						}
					}
				} else {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
							"尊敬的用户，您的验证码已经失效，请重新获取!"));
				}
			}
		} else {
			// 对证件验证
			List<Map<String, Object>> lists = IPtSmsRdDao.selectVerifyCode(map);
			if (lists.size() > 0) {
				flag = 0;
				return flag;
			} else {
				throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
						"未查询到相关证件信息，请核对您的证件和姓名是否正确！");
			}
		}

	}

	@Override
	// 查询所有卡信息
	public List<Map<String, Object>> getcardInfo(HashMap<String, Object> servParamMap) throws Exception {
		servParamMap.put("code", Constants.STRING_SERVICECODE_A09U003O);
		Map<String, Object> map = new HashMap<String, Object>(servParamMap);
		map.remove("queueId");
		logger.info("STRING_SERVICECODE_A09U003O:"+map.toString());
		String argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", map);
		// String argmsg="";
		/*
		 * if (Constants.GFY_ZHUSU_BIND.equals(servParamMap.get("is_bind"))) {
		 *
		 * argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?>"+ "<rows>"+
		 * "<row result=\"1\" message=\"绑定成功\" cardno=\"\" pathash=\"0x010000005a8d5f0df6e7c96460db4eeaece5d78b18f0ee805ef27b578273e2f30b8d1074\" is_bind=\"bind\" />"
		 * + "</rows>";
		 *
		 * }else if (Constants.GFY_ZHUSU_UNBIND.equals(servParamMap.get("is_bind"))) {
		 * argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?>"+ "<rows>"+
		 * "<row result=\"1\" message=\"解绑成功\" cardno=\"133**0001\" pathash=\"0x010000005a8d5f0df6e7c96460db4eeaece5d78b18f0ee805ef27b578273e2f30b8d1074\" is_bind=\"un_bind\" />"
		 * + "</rows>"; }else if
		 * (Constants.GFY_ZHUSU_NO.equals(servParamMap.get("is_bind"))) {
		 * argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?><rows></rows>";
		 * argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?>"+ "<rows>"+
		 * "<row result=\"1\" message=\"查询成功\" cardno=\"133**0001\" pathash=\"\" is_bind=\"no\" />"
		 * + "</rows>"; argmsg="<?xml version=\"1.0\" encoding=\"gbk\"?>"+ "<rows>"+
		 * "<row result=\"1\" message=\"查询成功\" cardno=\"188**0001\" pathash=\"\" is_bind=\"no\" />"
		 * + "</rows>"; }
		 */

		String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		servParamMap.put("updateTime", updateTime);
		servParamMap.put("updateAccept", updateAccept);
		servParamMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
		logger.info("%%%%%%%%%%%%%%%%%%%%%%  : " + argmsg);
		List<Map<String, Object>> list = ToolUtils.FormatXml(argmsg);
		logger.info("#########@@@@@@@@@@@@@@@@@@@@出参：" + list.toString());
		if (list != null && list.size() > 0) {
			if (Constants.GFY_ZHUSU_BIND.equals(servParamMap.get("is_bind"))) {
				// 绑卡时更新当前用户卡信息pt_queuescheme_info
				if (StringUtils.isEmpty(list.get(0).get("pathash"))) {
					/*
					 * list.clear(); Map<String, Object> mapIn = new HashMap<String, Object>();
					 * mapIn.put("message", list.get(0).get("message")); list.add(mapIn);
					 */
					list = null;
				} else {
					servParamMap.put("pathash", list.get(0).get("pathash"));
					servParamMap.put("cardName", Constants.GFY_ZHUSU_CARDNAME);
					logger.info("servParamMap" + servParamMap.toString());
					// 先入历史
					patientqueryCardDAO.PatientQueueSchemeHis(servParamMap);
					patientqueryCardDAO.updateCardThings(servParamMap);
				}

			} else if (Constants.GFY_ZHUSU_UNBIND.equals(servParamMap.get("is_bind"))) {
				// 解绑时更新当前用户卡信息pt_queuescheme_info 将card_status置为 0 失效
				logger.info("servParamMap--unbind" + servParamMap.toString());
				patientqueryCardDAO.PatientQueueSchemeHis(servParamMap);
				patientqueryCardDAO.updatestatusBypathash(servParamMap);
			} else {
				if (StringUtils.isEmpty(list.get(0).get("cardno"))) {
					list = null;
				}
			}
		} else {
			list = null;
		}
		// 解析出参
		// argmsg
		/*
		 * List<Map<String, Object>> lists = patientDao.selectcardinfo(servParamMap); if
		 * (lists != null && lists.size() > 0) { logger.info("#########" +
		 * lists.toString()); return lists; }
		 */
		return list;
	}

	@Override
	// 根据队列id和患者id查询用户是否参加当前队列
	public List<PatientQueueScheme> listSchemeInfo(HashMap<String, Object> qryPqsMap) throws Exception {
		List<PatientQueueScheme> lists = patientQueueSchemeDao.selectPatientByCondition(qryPqsMap);
		return lists;
	}

	// 获取患者信息通过phoneNo和username
	@Override
	@Transactional
	public Map<String, Object> getPatientinfoByphone(HashMap<String, Object> qryPqsMap) throws Exception {
		Map<String, Object> outRet = new HashMap<String, Object>();
		List<Patient> ptList = patientDao.selectByPhoneNo(qryPqsMap);
		if (CollectionUtils.isEmpty(ptList)) {
			ptList = patientqueryCardDAO.selectPtExtendUserInfo(qryPqsMap);
			if (CollectionUtils.isEmpty(ptList)) {
				ptList = patientqueryCardDAO.selectUserInfoByNameAndBir(qryPqsMap);
			}
		}
		String userId = "";
		boolean flag = false;
		// 通过患者姓名和手机号码查询该患者是否存在
		if (!CollectionUtils.isEmpty(ptList)) {
			flag = true;
			logger.info("2222222222222222222222" + flag);
			userId = ptList.get(0).getId();
			qryPqsMap.put("userId", userId);
			// 如果患者存在那么通过患者id和队列id查询该患者是否在当前队列中
			// 根据队列id和患者id查询用户是否参加当前队列
			List<PatientQueueScheme> Scheme = patientQueueSchemeDao.selectPatientByCondition(qryPqsMap);
			/*
			 * if (Scheme.size() > 0 && !Scheme.isEmpty()) { throw (new
			 * AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
			 * "尊敬的用户，当前宝宝已存在，请勿重复添加!")); }
			 */
			if (Scheme.size() > 0 && !Scheme.isEmpty()) {
				// 微信id更新接口
				patientDao.updateWechatId(qryPqsMap);
				outRet.put("patientId", userId);
				outRet.put("ptSchemeId", Scheme.get(0).getId());
				outRet.put("pathash", Scheme.get(0).getPathash());
				/*
				 * Map<String, Object> servParamMap = new LinkedHashMap<String, Object>();
				 * servParamMap.put("code", Constants.STRING_SERVICECODE_A09U003O);
				 * servParamMap.put("patName", ptList.get(0).getUserName());
				 * servParamMap.put("pattel", ptList.get(0).getPhoneNo());
				 * servParamMap.put("platform_code", Constants.SOURCE_TPLATFORM_CODE);
				 * servParamMap.put("platform_key", userId); servParamMap.put("pathash", "");
				 * servParamMap.put("is_bind", "no"); servParamMap.put("cardno", "");
				 * logger.info("重新绑定用户微信：" + servParamMap.toString()); String argmsg =
				 * bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", servParamMap);
				 * logger.info("argmsg   :  " + argmsg); List<Map<String, Object>> listone =
				 * ToolUtils.FormatXml(argmsg); logger.info("listone:出参：" + listone.toString());
				 * if (listone != null && listone.size() > 0 &&
				 * !StringUtils.isEmpty(listone.get(0).get("cardno"))) { outRet.put("status",
				 * "Y"); } else { String dateNow = DateUtil.getDateHm();// 获取当前时间 yyyy-mm-dd
				 * hh:mm String dateOrder = ""; int bigOne = -1; if
				 * (StringUtils.isEmpty(Scheme.get(0).getDate())) { } else { dateOrder =
				 * Scheme.get(0).getDate().toString(); bigOne = dateOrder.compareTo(dateNow); }
				 * logger.info("bigOne:" + bigOne); if (bigOne > 0 &&
				 * !StringUtils.isEmpty(Scheme.get(0).getReservationId())) {
				 * outRet.put("status", "Y"); } else { outRet.put("status", "N"); }
				 *
				 * }
				 */
			}
		}
		outRet.put("flag", flag);
		return outRet;
	}

	// 获取患者信息通过患者id更新微信id
	@Override
	@Transactional
	public void updateWechatId(HashMap<String, Object> qryPqsMap) throws Exception {
		patientDao.updateWechatId(qryPqsMap);
	}

	// 获取队列信息
	@Override
	public Map<String, Object> selectByIdALL(Map<String, Object> qryPqsMap) throws Exception {
		HashMap<String, Object> argMap = new HashMap<String, Object>(qryPqsMap);
		HashMap<String, Object> retOutMap = new HashMap<String, Object>();

		String patientId = argMap.get("patientId").toString();
		String queueId = argMap.get("queueId").toString();
		String type = argMap.get("type").toString();

		String followDeptId = "";// 科室id
		// String custValType = (String) argMap.get("custValType");//
		// 客户标识，安医大特殊处理
		String opType = "";
		if (StringUtils.isEmpty(argMap.get("opType")) && argMap.get("opType") != null) {
			opType = argMap.get("opType").toString();// 是否需要查询实例化模板
		}
		// 校验患者信息是否存在
		Map<String, Object> userMapIn = new HashMap<String, Object>();
		userMapIn.put("userId", patientId);
		Patient ptVo = patientDao.selectById(userMapIn);
		// System.out.println("333333333333333333333333333333" );
		if (null == ptVo || "".equals(ptVo.getId())) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询随访系统无此患者！"));
		}
		userMapIn.clear();
		userMapIn.put("userId", patientId);
		userMapIn.put("queueId", queueId);
		// System.out.println("11111111111111111111111" );
		List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(userMapIn);
		// System.out.println("222222222222222222222" );
		if (CollectionUtils.isEmpty(pqsList)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "队列实例表中无此患者信息！");
		}
		PatientQueueScheme psVo = pqsList.get(0);
		String userStatus = psVo.getUserStatus();
		if (!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(userStatus)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_NOT_NORMAL,
					"患者在该队列中状态异常，无法进行相关操作！");
		}

		String taskId = "";
		HashMap<String, Object> taskInMap = new HashMap<String, Object>();
		taskInMap.put("ptSchemeId", psVo.getId());
		taskInMap.put("endTime", DateUtil.getCurrDate());
		taskInMap.put("beginTime", DateUtil.getCurrDate());
		taskInMap.put("revSeqNo", 0);// 去掉建档任务
		// System.out.println("333333333333333333333333333" );
		List<PatientTask> ptVoList = patientTaskDao.select(taskInMap);
		// System.out.println("4444444444444444444444444" );
		if (CollectionUtils.isEmpty(ptVoList)) {
			// if (!StringUtils.isEmpty(custValType)) {
			// 若没有当前窗口期的任务，则用第一次随访任务替代(针对安医大项目)
			taskInMap.clear();
			taskInMap.put("ptSchemeId", psVo.getId());
			taskInMap.put("seqNo", 1);
			// System.out.println("5555555555555555555555555" );
			ptVoList = patientTaskDao.select(taskInMap);
			// System.out.println("666666666666666666666666" );
			if (CollectionUtils.isEmpty(ptVoList)) {
				// throw new
				// AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_TASK_NOT_EXIST,
				// "该患者无任务信息！");
				return retOutMap;
			}
			/*
			 * } else { return retOutMap; }
			 */
		}
		PatientTask ptTaskVo = ptVoList.get(0);
		taskId = ptTaskVo.getId();

		taskInMap.clear();
		taskInMap.put("taskId", taskId);
		taskInMap.put("contTemplType", type);// 问卷模板类型
		taskInMap.put("userId", patientId);
		List<Object> conDataList = new ArrayList<Object>();
		List<Object> bloodSugar = new ArrayList<Object>();
		List<Object> food = new ArrayList<Object>();
		List<Object> excrcise = new ArrayList<Object>();
		Map<String, Object> mapALLquestion = new HashMap<String, Object>();
		// System.out.println("7777777777777777777777" );
		List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(taskInMap);
		// System.out.println("8888888888888888888888888" );
		if (!CollectionUtils.isEmpty(ptcList)) {
			// questiones
			int ipt = 0;
			int isize = ptcList.size();
			Map<String, Object> dataOut = new HashMap<String, Object>();
			Map<String, Object> contVerMap = new HashMap<String, Object>();
			for (ipt = 0; ipt < isize; ipt++) {
				PatientTaskContent ptaskc = ptcList.get(ipt);
				// 获取内容模板
				contVerMap.clear();
				contVerMap.put("templVersionId", ptaskc.getTemplVersionid());
				contVerMap.put("taskId", taskId);
				contVerMap.put("ptSchemeId", psVo.getId());
				contVerMap.put("userId", patientId);
				contVerMap.put("opType", opType);
				if (StringUtils.isEmpty(opType)) {
					// System.out.println("8888888888888888888888" );
					dataOut = patientSerivce.getContTemplData(contVerMap);
					// System.out.println("999999999999999999" );
					if (null != dataOut.get("contData")) {
						conDataList.add(dataOut.get("contData"));
					}

					retOutMap.put("questiones", conDataList);

				} else {
					dataOut = AppPatientAotuService.getContent(contVerMap);
					// 分类：0：血糖问卷 1：餐谱问卷 2：运动问卷
					int typecode = Integer.parseInt(dataOut.get("typeCode").toString().trim());
					switch (typecode) {
					case 0:
						bloodSugar.add(dataOut.get("contData"));
						break;
					case 1:
						food.add(dataOut.get("contData"));
						break;
					case 2:
						excrcise.add(dataOut.get("contData"));
						break;
					}
					mapALLquestion.put("bloodSugar", bloodSugar);
					mapALLquestion.put("food", food);
					mapALLquestion.put("excrcise", excrcise);

					retOutMap.put("questiones", mapALLquestion);
				}

			}
			// values:上次填写的答案
			HashMap<String, Object> valuesMap = new HashMap<String, Object>();
			HashMap<String, Object> valuesMapOne = new HashMap<String, Object>();
			HashMap<String, Object> valuesMapTow = new HashMap<String, Object>();
			HashMap<String, Object> valuesMapThere = new HashMap<String, Object>();
			// List <Map<String,Object>> lists = new
			// ArrayList<Map<String,Object>>();
			HashMap<String, Object> mapInto = new HashMap<String, Object>();
			Map<String, Object> valMapIn = new HashMap<String, Object>();
			valMapIn.put("taskId", taskId);
			valMapIn.put("contDataTemplType", type);
			if (!StringUtils.isEmpty(opType)) {
				argMap.put("id", queueId);
				List<FollowQueue> list = queueDao.selectById(argMap);
				followDeptId = list.get(0).getDeptId();
				valMapIn.put("queryCondition", "Y");// 需要增加条件
			}
			// logger.info("valMapIn****"+valMapIn.toString());
			// System.out.println("0202232323232322" );
			List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(valMapIn);
			// System.out.println("4543545354543" );
			if (!CollectionUtils.isEmpty(ptTaskConList)) {
				int k = 0;
				if (StringUtils.isEmpty(opType)) {
					logger.info("111111111111111111111" + opType);
					for (; k < ptTaskConList.size(); k++) {
						PatientContentData pcdVo = ptTaskConList.get(k);
						valuesMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
					}
					retOutMap.put("values", valuesMap);
				} else {
					for (; k < ptTaskConList.size(); k++) {
						PatientContentData pcdVo = ptTaskConList.get(k);
						if ("0".equals(pcdVo.getOpType())) {
							valuesMapOne.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
						} else if ("1".equals(pcdVo.getOpType())) {
							valuesMapTow.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
						} else {
							valuesMapThere.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
						}
					}
					mapInto.put("bloodSugar", valuesMapOne);
					mapInto.put("food", valuesMapTow);
					mapInto.put("excrcise", valuesMapThere);
					/*
					 * lists.add(0, valuesMapOne); lists.add(1, valuesMapTow); lists.add(2,
					 * valuesMapThere);
					 */
					retOutMap.put("values", mapInto);
				}

			} else {
				retOutMap.put("values", mapInto);
			}
		}

		// task
		Map<String, Object> taskMap = new HashMap<String, Object>();
		taskMap.put("ptTaskId", taskId);
		taskMap.put("ptTaskName", ptTaskVo.getTaskName());
		taskMap.put("seqNo", ptTaskVo.getSeqNo());
		taskMap.put("type", type);
		retOutMap.put("taskInfo", taskMap);

		// ptQueue
		HashMap<String, Object> oprInfoMap = new HashMap<String, Object>();
		oprInfoMap.put("patientId", ptTaskVo.getUserId());
		oprInfoMap.put("ptSchemeId", ptTaskVo.getPtSchemeid());
		oprInfoMap.put("followQueueId", queueId);
		oprInfoMap.put("followDeptId", followDeptId);
		retOutMap.put("ptQueueInfo", oprInfoMap);
		// logger.info("4444444444444444444");
		return retOutMap;
	}

	// 月度评估提交信息
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public Map<String, Object> registerMonthCommit(Map<String, Object> qryPqsMap) throws Exception {
		logger.info("selectUserIdByPhoneNo~~~in" + qryPqsMap.toString());
		Map<String, Object> qryPtMap = new HashMap<String, Object>();
		Map<String, Object> outMap = new HashMap<String, Object>();
		String queueId = (String) qryPqsMap.get("queueId");
		String updateTime = (String) qryPqsMap.get("updateTime");
		String authorId = (String) qryPqsMap.get("authorId");
		String updateAccept = (String) qryPqsMap.get("updateAccept");
		String tenantId = (String) qryPqsMap.get("tenantId");
		String authorName = (String) qryPqsMap.get("authorName");
		String opCode = (String) qryPqsMap.get("opCode");
		String opType = (String) qryPqsMap.get("opType");
		Patient ptNew = (Patient) qryPqsMap.get("patient");
        String sourceType = (String) qryPqsMap.get("sourceType");
		qryPtMap.put("phoneNo", ptNew.getPhoneNo());
		qryPtMap.put("userName", ptNew.getUserName());
		qryPtMap.put("tenantId", qryPqsMap.get("tenantId"));
		List<Patient> ptList = patientDao.selectByPhoneNo(qryPtMap);
		logger.info("wwwwwwwwwwwwwwwwwwwwwwwwww：出参：" + ptList.toString());
		Map<String, Object> quesMap = (JSONObject) qryPqsMap.get("contentData");
		String birthWeight = "";
		if (null != quesMap) {
			birthWeight = (null == quesMap.get(Constants.QUESTION_ID_FOR_WEIGHT)) ? null
					: quesMap.get(Constants.QUESTION_ID_FOR_WEIGHT).toString();
		}

		String ptSchemeid = "";
		String taskId = "";
		if (CollectionUtils.isEmpty(ptList)) {
			// return outMap;
			outMap = patientSerivce.registerPatient(qryPqsMap);
		} else {
			Patient pt = ptList.get(0);
			// 校验患者是否已经加入过该队列
			qryPqsMap.put("userId", pt.getId());
			qryPqsMap.put("queueId", qryPqsMap.get("queueId"));
			List<String> statulist = new ArrayList<String>();// 查询出暂停和正常 两个状态
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND);
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_AUDIT); // 待审核状态
			qryPqsMap.put("status", statulist);
			List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(qryPqsMap);
			if (null != pqsList && 0 != pqsList.size()) {
				if (Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND.equals(pqsList.get(0).getUserStatus())) {
					logger.error("该患者[" + pt.getUserName() + "]为暂停状态，可直接恢复！");
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_SUSPEND,
							"该患者[" + pt.getUserName() + "]为暂停状态，请恢复患者为管理状态！"));
				} else if (Constants.PATIENT_QUEUESCHEME_USER_STATUS_AUDIT.equals(pqsList.get(0).getUserStatus())) {
					logger.error("该患者[" + pt.getUserName() + "]为待审核状态，请审批完再添加！");
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_AUDIT,
							"该患者[" + pt.getUserName() + "]为待审核状态，请进入审批列表审批即可"));
				} else {
					// 修改基本信息
					// 修改用户姓名信息 ，加入其它队列时候 不再重新创建基本用户
					qryPtMap.clear();
					qryPtMap.put("userId", pt.getId());
					qryPtMap.put("updateTime", updateTime);
					qryPtMap.put("birthday", ptNew.getBirthday());
					qryPtMap.put("expectedDay", ptNew.getExpectedDay());
					qryPtMap.put("gender", ptNew.getGender());
					qryPtMap.put("pregnancyDay", ptNew.getPregnancyDay());
					List<String> tenantIdList = new ArrayList<String>();
					tenantIdList.add(tenantId);
					tenantIdList.add(Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
					qryPtMap.put("tenantIdList", tenantIdList);
					// qryPtMap.put("userType","1");
					// 修改当前租户id和默认0的基本信息
					patientDao.updatePatientInfoById(qryPtMap);

					// 历史表记录
					Map<String, Object> userHisMap = new HashMap<String, Object>();
					userHisMap.put("userId", pt.getId());
					userHisMap.put("updateTime", updateTime);
					userHisMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
					userHisMap.put("tenantIdList", tenantIdList);
					patientDao.savePatientHisInfo(userHisMap);

					ptSchemeid = pqsList.get(0).getId();
					Map<String, Object> taskMap = new HashMap<String, Object>();
					taskMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
					taskMap.put("ptSchemeId", ptSchemeid);

					// 查询taskid
					List<PatientTask> taskList = patientTaskDao.select(taskMap);
					if (!CollectionUtils.isEmpty(taskList)) {
						taskId = taskList.get(0).getId();
					}
					// 解析建档任务内容（问卷）
					if (null == quesMap || 0 == quesMap.size()) {
						logger.warn("无建档问卷问题--答案记录");
					} else {
						List<PatientContentData> ptcInList = new ArrayList<PatientContentData>();
						List<PatientContentData> ptcInListHis = new ArrayList<PatientContentData>();
						Iterator<String> iter = quesMap.keySet().iterator();

						// 答题正表 修改
						Map<String, Object> ptUpMapIn = new HashMap<String, Object>();
						String contTemplType = "";
						String opTime = "";
						if (Constants.OP_TYPE_DOOR.equals(ptNew.getSourceType())) {
							contTemplType = Constants.QUESTIONNAIRE_TYPE_0;
						}
						int pr = 0;
						while (iter.hasNext()) {
							PatientContentData pcdVo = new PatientContentData();
							String queskey = iter.next();
							String quesvalue = (String) quesMap.get(queskey);

							ptUpMapIn.put("questionAnswer", quesvalue);
							ptUpMapIn.put("questionId", queskey);
							ptUpMapIn.put("taskId", taskId);
							ptUpMapIn.put("updateAccept", updateAccept);
							ptUpMapIn.put("updateTime", updateTime);
							ptUpMapIn.put("templType", contTemplType);
							ptUpMapIn.put("opTime", opTime);
							ptUpMapIn.put("sourceTypeUpdate", sourceType);
							pr = patientTaskConDao.updatePtContentDataInfoByConDt(ptUpMapIn);

							pcdVo.setContentId("");
							pcdVo.setCreateTime(updateTime);
							pcdVo.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
							pcdVo.setQuestionAnswer(quesvalue);
							pcdVo.setQuestionId(queskey);
							pcdVo.setTaskId(taskId);
							pcdVo.setUpdateAccept(updateAccept);
							pcdVo.setUpdateTime(updateTime);
							pcdVo.setUpdateType(Constants.UPDATE_TYPE_INSERT);
							pcdVo.setUserId(pt.getId());
							pcdVo.setPtSchemeid(ptSchemeid);
							pcdVo.setQueueId(queueId);
				            pcdVo.setTenantId(tenantId);
				            pcdVo.setSourceTypeCreate(sourceType);
				            pcdVo.setSourceTypeUpdate(sourceType);
							ptcInListHis.add(pcdVo); // 进历史

							if (0 == pr) {
								ptcInList.add(pcdVo); // 新增加题目 则插入
							}
						}
						// 批量插入
						if (!CollectionUtils.isEmpty(ptcInList)) {
							patientTaskConDao.savePatientTaskContentDataBatch(ptcInList);
						}
						patientTaskConDao.savePatientTaskContentDataHisBatch(ptcInListHis);
					}

					// 入操作流水记录表 ia_operation_record
					String opUserType = Constants.OPCODE_TYPE_DOCTOR;
					if (Constants.OP_TYPE_SELF.equals(ptNew.getSourceType())) {
						opUserType = Constants.OPCODE_TYPE_PATIENT;
					}

					Map<String, Object> paramRecord = new HashMap<String, Object>();
					paramRecord.put("userName", ptNew.getUserName());
					paramRecord.put("userId", pt.getId());
					paramRecord.put("queueId", queueId);
					paramRecord.put("authorId", authorId);
					paramRecord.put("opTime", updateTime);

					if (Constants.OP_CODE_1004.equals(opCode)) {// 队列患者转移
						paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_11);
					} else if ((Constants.OP_CODE_1000.equals(opCode))) {
						paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_7);
					}
					paramRecord.put("opUsertype", opUserType);
					paramRecord.put("authorName", authorName);
					paramRecord.put("opCode", opCode);
					paramRecord.put("updateAccept", updateAccept);
					paramRecord.put("tenantId", tenantId);
					if (qryPqsMap.get("opNote") == null && "".equals(qryPqsMap.get("opNote").toString())) {
						String remark = "患者" + pt.getUserName() + "通过app进行主诉登记";
						paramRecord.put("remark", remark);
					} else {
						paramRecord.put("remark", (String) qryPqsMap.get("opNote"));
					}
					paramRecord.put("opType", opType);
					if (!StringUtils.isEmpty(taskId)) {
						paramRecord.put("taskId", taskId);
					}
					Map<String, Object> outRecord = patientInfoHisService.buildOperationRecord(paramRecord);
					patientOperationRecordDao.saveOperationRecord(outRecord);
					outMap.put("patientId", pt.getId());
				}
			} else {
				outMap = patientSerivce.registerPatient(qryPqsMap);
			}
		}

		String testTime = DateUtil.getCurrDate2();
		String userId = (String) outMap.get("patientId");
		// 更新用户基本信息
		if (outMap != null && outMap.size() > 0) {
			// 身高
			String weight = (String) quesMap.get(Constants.QUESTION_ID_FOR_GROWTHDEV_WEIGHT);
			// 体重
			String height = (String) quesMap.get(Constants.QUESTION_ID_FOR_GROWTHDEV_HEIGHT);
			// 头围
			String headCircumference = (String) quesMap.get(Constants.QUESTION_ID_FOR_GROWTHDEV_HEADCIRCUM);

			if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(weight) || StringUtils.isEmpty(height)
					|| StringUtils.isEmpty(headCircumference)) {
				// return new ResultModel<Map<String, Object>>(userMap);
			} else {
				Map<String, Object> Map = new HashMap<String, Object>();
				Map.put("userId", userId);
				Map.put("weight", weight);
				Map.put("height", height);
				Map.put("tenantId", tenantId);
				Map.put("testTime", testTime);
				Map.put("sourceType", Constants.SOURCE_TYPE_WECHAT);
				Map.put("headCircumference", headCircumference);
				Map.put("submitId", updateAccept);
				Map<String, Object> retOut = familyReportService.addGrowthRecord(Map);
				outMap.put("retOut", retOut);
			}
		}
		ptNew.setId(userId);

		com.alibaba.fastjson.JSONArray answers = (null == qryPqsMap.get("answers")) ? null
				: (com.alibaba.fastjson.JSONArray) qryPqsMap.get("answers");
		// 月度评估问卷 增加智能发育和养育环境 （可选）评估
		if (null != answers && answers.size() > 0) {
			JSONObject obj = null;
			String testTime2 = DateUtil.getDate_8(new Date());
			for (int i = 0; i < answers.size(); i++) {
				obj = answers.getJSONObject(i);
				String evaluationType = "";
				String postionIds = "";
				if (null != obj) {
					// 问卷结果保存入库
					List<PtEvaluationGuide> guideList = new ArrayList<PtEvaluationGuide>();
					PtEvaluationResult answer = new PtEvaluationResult();
					evaluationType = obj.getString("evaluationType");
					postionIds = obj.getString("postionIds");
					Map<String, Object> paramsMap = new HashMap<String, Object>();
					if (Constants.FOLLOW_EVALUATION_PREGNANT_AHEMD.equals(evaluationType)) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("Patient", ptNew);
						map.put("postionIds", postionIds);
						map.put("evaluationType", evaluationType);
						paramsMap = followEvaluationScoreService.getAhemdScore(map);
						if (null != paramsMap.get("guideList")) {
							guideList = (List<PtEvaluationGuide>) paramsMap.get("guideList");
							paramsMap.remove("guideList");
						}
					} else if (Constants.FOLLOW_EVALUATION_PREGNANT_ASQ.equals(evaluationType)) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("Patient", ptNew);
						map.put("postionIds", postionIds);
						map.put("evaluationType", evaluationType);
						paramsMap = followEvaluationScoreService.getAsqScore(map);
						if (null != paramsMap.get("guideList")) {
							guideList = (List<PtEvaluationGuide>) paramsMap.get("guideList");
							paramsMap.remove("guideList");
						}
					}

					answer.setType(evaluationType);
					answer.setId(SeqUtil.getSeqNo());
					answer.setCreateTime(DateUtil.getSysDateA());
					answer.setScore(JSON.toJSONString(paramsMap));
					answer.setResult(postionIds);
					answer.setSourcetype(Constants.SOURCE_TYPE_WECHAT); // APP或微信录入
					answer.setSourceid(userId);
					answer.setTenantId(tenantId);
					answer.setUserId(userId);
					// answer.setTaskId(taskId);
					answer.setTestTime(testTime2);
					answer.setSubmitId(updateAccept); // 一次月度评估id
					followEvaluationService.savePtEvaluationResult(answer, guideList);
				}
			}
		}

		PtEvaluationOrder workORder = new PtEvaluationOrder();
		workORder.setCreateAuthor(authorId);
		workORder.setCreateTime(updateTime);
		workORder.setId(updateAccept);
		workORder.setQueueId(queueId);
		workORder.setRemark1(birthWeight);
		workORder.setStatus(Constants.EVLATATION_WORKORDER_STATUS_INIT);
		workORder.setTenantId(tenantId);
		workORder.setUserId(userId);
		workORder.setWorkOrderId(updateAccept);
		workORder.setWechatId(ptNew.getWechat_id());
		evaluationWorkOrderDAO.savePtEvaluationOrder(workORder);
		outMap.put("workOrderId", workORder.getId());
		return outMap;
	}

	// 查询当前用户是否在当前队列中
	@Override
	@Transactional
	public Map<String, Object> selectUserIdByPhoneNo(Map<String, Object> qryPqsMap) throws Exception {
		logger.info("selectUserIdByPhoneNo~~~in" + qryPqsMap.toString());
		Map<String, Object> qryPtMap = new HashMap<String, Object>();
		Map<String, Object> outMap = new HashMap<String, Object>();
		String queueId = (String) qryPqsMap.get("queueId");
		String updateTime = (String) qryPqsMap.get("updateTime");
		String authorId = (String) qryPqsMap.get("authorId");
		String updateAccept = (String) qryPqsMap.get("updateAccept");
		String tenantId = (String) qryPqsMap.get("tenantId");
		String authorName = (String) qryPqsMap.get("authorName");
		String opCode = (String) qryPqsMap.get("opCode");
		String opType = (String) qryPqsMap.get("opType");
		String sourceType = (String) qryPqsMap.get("sourceType");
		Patient pt = (Patient) qryPqsMap.get("patient");
		qryPtMap.put("phoneNo", pt.getPhoneNo());
		qryPtMap.put("userName", pt.getUserName());
		qryPtMap.put("tenantId", qryPqsMap.get("tenantId"));
		List<Patient> ptList = patientDao.selectByPhoneNo(qryPtMap);
		logger.info("wwwwwwwwwwwwwwwwwwwwwwwwww：出参：" + ptList.toString());
		Map<String, Object> quesMap = (JSONObject) qryPqsMap.get("contentData");
		String ptSchemeid = "";
		String taskId = "";
		if (CollectionUtils.isEmpty(ptList)) {
			return outMap;
		} else {
			pt = ptList.get(0);
			// 校验患者是否已经加入过该队列
			qryPqsMap.put("userId", pt.getId());
			qryPqsMap.put("queueId", qryPqsMap.get("queueId"));
			List<String> statulist = new ArrayList<String>();// 查询出暂停和正常 两个状态
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND);
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
			statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_AUDIT); // 待审核状态
			qryPqsMap.put("status", statulist);
			List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(qryPqsMap);
			if (null != pqsList && 0 != pqsList.size()) {
				if (Constants.PATIENT_QUEUESCHEME_USER_STATUS_SUSPEND.equals(pqsList.get(0).getUserStatus())) {
					logger.error("该患者[" + pt.getUserName() + "]为暂停状态，可直接恢复！");
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_SUSPEND,
							"该患者[" + pt.getUserName() + "]为暂停状态，请恢复患者为管理状态！"));
				} else if (Constants.PATIENT_QUEUESCHEME_USER_STATUS_AUDIT.equals(pqsList.get(0).getUserStatus())) {
					logger.error("该患者[" + pt.getUserName() + "]为待审核状态，请审批完再添加！");
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_AUDIT,
							"该患者[" + pt.getUserName() + "]为待审核状态，请进入审批列表审批即可"));
				} else {
					ptSchemeid = pqsList.get(0).getId();
					Map<String, Object> taskMap = new HashMap<String, Object>();
					taskMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
					taskMap.put("ptSchemeId", ptSchemeid);
					// 查询taskid
					List<PatientTask> taskList = patientTaskDao.select(taskMap);
					if (!CollectionUtils.isEmpty(taskList)) {
						taskId = taskList.get(0).getId();
					}
					// 解析建档任务内容（问卷）
					if (null == quesMap || 0 == quesMap.size()) {
						logger.warn("无建档问卷问题--答案记录");
					} else {
						List<PatientContentData> ptcInList = new ArrayList<PatientContentData>();
						Iterator<String> iter = quesMap.keySet().iterator();
						while (iter.hasNext()) {
							PatientContentData pcdVo = new PatientContentData();
							String queskey = iter.next();
							String quesvalue = (String) quesMap.get(queskey);

							pcdVo.setContentId("");
							pcdVo.setCreateTime(updateTime);
							pcdVo.setId(SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_PTTASK_CONTDATAID));
							pcdVo.setQuestionAnswer(quesvalue);
							pcdVo.setQuestionId(queskey);
							pcdVo.setTaskId(taskId);
							pcdVo.setUpdateAccept(updateAccept);
							pcdVo.setUpdateTime(updateTime);
							pcdVo.setUpdateType(Constants.UPDATE_TYPE_INSERT);
							pcdVo.setUserId(pt.getId());
							pcdVo.setPtSchemeid(ptSchemeid);
							if (Constants.OP_TYPE_DOOR.equals(pt.getSourceType())) {
								pcdVo.setTemplType(Constants.QUESTIONNAIRE_TYPE_0);
							} else {
								// 非门诊问卷，后续补充
								pcdVo.setTemplType("");
							}
							pcdVo.setQueueId(queueId);
                            pcdVo.setTenantId(tenantId);
                            pcdVo.setSourceTypeCreate(sourceType);
                            pcdVo.setSourceTypeUpdate(sourceType);
							ptcInList.add(pcdVo);
						}
						// 批量插入
						patientTaskConDao.savePatientTaskContentDataBatch(ptcInList);
						patientTaskConDao.savePatientTaskContentDataHisBatch(ptcInList);
					}

					// 入操作流水记录表 ia_operation_record
					String opUserType = Constants.OPCODE_TYPE_DOCTOR;
					if (Constants.OP_TYPE_SELF.equals(pt.getSourceType())) {
						opUserType = Constants.OPCODE_TYPE_PATIENT;
					}
					Map<String, Object> paramRecord = new HashMap<String, Object>();
					paramRecord.put("userName", pt.getUserName());
					paramRecord.put("userId", pt.getId());
					paramRecord.put("queueId", queueId);
					paramRecord.put("authorId", authorId);
					paramRecord.put("opTime", updateTime);

					if (Constants.OP_CODE_1004.equals(opCode)) {// 队列患者转移
						paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_11);
					} else if ((Constants.OP_CODE_1000.equals(opCode))) {
						paramRecord.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_7);
					}
					paramRecord.put("opUsertype", opUserType);
					paramRecord.put("authorName", authorName);
					paramRecord.put("opCode", opCode);
					paramRecord.put("updateAccept", updateAccept);
					paramRecord.put("tenantId", tenantId);
					if (qryPqsMap.get("opNote") == null && "".equals(qryPqsMap.get("opNote").toString())) {
						String remark = "患者" + pt.getUserName() + "通过app进行主诉登记";
						paramRecord.put("remark", remark);
					} else {
						paramRecord.put("remark", (String) qryPqsMap.get("opNote"));
					}
					paramRecord.put("opType", opType);
					if (!StringUtils.isEmpty(taskId)) {
						paramRecord.put("taskId", taskId);
					}
					Map<String, Object> outRecord = patientInfoHisService.buildOperationRecord(paramRecord);
					patientOperationRecordDao.saveOperationRecord(outRecord);
					outMap.put("patientId", pt.getId());
				}

			}
			return outMap;
		}

	}

	// 查询微信用户月度评估信息
	@Override
	public List<Map<String, Object>> selectTotle(HashMap<String, Object> qryPqsMap) throws Exception {
		logger.info("selectTotle()~~~~~~~~：" + qryPqsMap.toString());
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> qryPtMap = new HashMap<String, Object>();
		String queueId = (String) qryPqsMap.get("queueId");

		List<Map<String, Object>> listTotle = new ArrayList<Map<String, Object>>();
		qryPtMap.put("phoneNo", qryPqsMap.get("phoneNo"));
		qryPtMap.put("userName", qryPqsMap.get("userName"));
		qryPtMap.put("tenantId", qryPqsMap.get("tenantId"));
		if (qryPqsMap.get("page") != null && !"".equals(qryPqsMap.get("page"))) {
			int page = (qryPqsMap.get("page") != null && !StringUtils.isEmpty(qryPqsMap.get("page").toString()))
					? Integer.parseInt(qryPqsMap.get("page").toString())
					: 1;
			int rows = (qryPqsMap.get("rows") != null && !StringUtils.isEmpty(qryPqsMap.get("rows").toString()))
					? Integer.parseInt(qryPqsMap.get("rows").toString())
					: 10;
			map.put("start", rows * (page - 1));
			map.put("end", rows);
		} else {
			map.put("start", 0);
			map.put("end", Constants.APP_ROWS_FOR_INIT);
		}
		String userId = "";
		if (!StringUtils.isEmpty(qryPtMap.get("phoneNo"))) {
			List<Patient> ptList = patientDao.selectByPhoneNo(qryPtMap);
			userId = ptList.get(0).getId();
		}
		map.put("queueId", queueId);
		map.put("userId", userId);
		map.put("opCode", qryPqsMap.get("opCode"));
		map.put("fieldName", qryPqsMap.get("fieldName"));
		map.put("order", qryPqsMap.get("order"));
		logger.info("map.toString()~~~~~~~~：" + map.toString());
		List<Map<String, Object>> list = patientOperationRecordDao.selectOperationByUserId(map);
		logger.info("patientOperationRecordDao()~~~~~~~~：" + list.toString());
		if (!CollectionUtils.isEmpty(list)) {
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> mapIn = new HashMap<String, Object>();
				mapIn.put("taskId", list.get(i).get("TASK_ID"));
				mapIn.put("updateAccept", list.get(i).get("ID"));
				List<PatientContentData> lists = patientTaskConDao.selectCntDataHisByTaskIdAndAccept(mapIn);
				Map<String, Object> mapInOne = new HashMap<String, Object>();
				mapInOne.put("id", list.get(i).get("ID"));
				mapInOne.put("opTime", DateUtil.getTimeStampSec(list.get(i).get("OP_TIME").toString()));
				for (int j = 0; j < lists.size(); j++) {
					mapInOne.put(lists.get(j).getQuestionId(), lists.get(j).getQuestionAnswer());
				}
				listTotle.add(i, mapInOne);
			}
		} else {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_STATUS_SUSPEND,
					"没有查询到当前用户月度评估信息！"));
		}
		Collections.sort(listTotle, new TestComparator());
		logger.info("listTotle@@@" + listTotle.toString());
		return listTotle;
	}

	// 查询患者门诊随访信息业务逻辑
	@Override
	public Map<String, Object> selectPtOnlineTaskInfo(Map<String, Object> qryPqsMap) throws Exception {
		logger.info("selectPtOnlineTaskInfo()~~~~~~~~：" + qryPqsMap.toString());
		// 获取入参信息
		HashMap<String, Object> argMap = new HashMap<String, Object>(qryPqsMap);
		// 定义出参容器
		HashMap<String, Object> retOutMap = new HashMap<String, Object>();

		// 取出具体入参
		String patientId = (String) argMap.get("patientId");
		String appDeptId = (String) argMap.get("departmentId");
		String queueId = (String) argMap.get("queueId");
		String type = (String) argMap.get("type");

		// 校验患者信息是否存在
		Map<String, Object> userInMap = new HashMap<String, Object>();
		userInMap.put("userId", patientId);
		userInMap.put("tenantId", Constants.PT_USER_INFO_DEFAULT_TENANT_ID);

		// 查询患者信息
		Patient ptVo = patientDao.selectById(userInMap);
		if (null == ptVo || StringUtils.isEmpty(ptVo.getId())) {
			logger.error("随访系统无此患者【" + patientId + "】信息！");
			return retOutMap;// 老随访数据未刷，这里为了友好展示，直接返回空给app端
		}

		// 找到app科室id对应的随访科室id
		String followDeptId = "";
		if (!StringUtils.isEmpty(appDeptId)) {
			Map<String, Object> deptBasicMap = new HashMap<String, Object>();
			deptBasicMap.put("refDeptId", appDeptId);
			List<DepartmentBasic> deptList = departBasicDao.selectByRefDeptId(deptBasicMap);
			if (CollectionUtils.isEmpty(deptList)) {
				logger.error("未查询到关联科室id！");
				return retOutMap;// 老随访数据未刷，这里为了友好展示，直接返回空给app端
			}
			followDeptId = deptList.get(0).getId();
		}

		// 定义接收当前科室id下的队列信息容器
		List<String> queueIdList = new ArrayList<String>();
		// 判断科室id是否存在
		if (!StringUtils.isEmpty(followDeptId)) {
			// 定义入参容器
			Map<String, Object> queueMapIn = new HashMap<String, Object>();
			queueMapIn.put("deptId", followDeptId);

			// 根据科室id查询该科室下的队列id
			List<FollowQueue> queueList = queueDao.selectByDeptId(queueMapIn);

			// 判断当前科室id下是否有队列信息
			if (CollectionUtils.isEmpty(queueList)) {
				logger.error("该科室id下未配置队列！");
				return retOutMap;// 老随访数据未刷，这里为了友好展示，直接返回空给app端
			}

			// 实例化一个对象
			FollowQueue fqVo = new FollowQueue();
			int qsize = queueList.size();
			int k = 0;
			for (k = 0; k < qsize; k++) {
				// 判断队列状态是否正常
				fqVo = queueList.get(k);
				if (Constants.QUEUE_STATUS_NOMAL.equals(fqVo.getQueueStatus())) {
					queueIdList.add(fqVo.getId());
				}
			}
		} else {
			// 入参传的是队里id
			argMap.put("id", queueId);
			List<FollowQueue> list = queueDao.selectById(argMap);
			followDeptId = list.get(0).getDeptId();
			queueIdList.add(queueId);
		}

		// 如果没有队列信息则直接返回
		if (CollectionUtils.isEmpty(queueIdList)) {
			return retOutMap;
		}

		// 定义查询队列实例化信息入参容器
		Map<String, Object> quMap = new HashMap<String, Object>();
		quMap.put("userId", patientId);
		quMap.put("queueIdIn", queueIdList);

		// 查询患者队列实例化信息
		List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectByUserId(quMap);
		// 判断患者是否加入当前队列
		if (CollectionUtils.isEmpty(pqsList)) {
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "该患者未加入相关队列！");
		}
		// 地址类型
		List<String> addressList = new ArrayList<String>();
		List<String> dateList = new ArrayList<String>();
		// 定义接收任务信息容器
		List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
		int totalNum = 0;// 问卷个数
		int num = 0;
		// 循环信息
		for (int t = 0; t < pqsList.size(); t++) {
			PatientQueueScheme psVo = pqsList.get(t);
			String userStatus = psVo.getUserStatus();
			if (!Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL.equals(userStatus)) {
				logger.warn("患者在该队列【" + psVo.getQueueId() + "】中状态异常，无法进行相关操作！");
				continue;
			}

			// 任务id
			String taskId = "";
			// 查询窗口期内的任务入参
			HashMap<String, Object> taskInMap = new HashMap<String, Object>();
			taskInMap.put("ptSchemeId", psVo.getId());
			taskInMap.put("endTime", DateUtil.getCurrDate());
			taskInMap.put("beginTime", DateUtil.getCurrDate());
			taskInMap.put("seqNoOrderAsc", "seqNoOrderAsc");
			taskInMap.put("taskType", "0");
			taskInMap.put("taskStatus", "0");
			taskInMap.put("revSeqNo", 0);// 去掉建档任务

			// 查询所有的任务信息
			List<PatientTask> ptVoList = patientTaskDao.select(taskInMap);
			taskInMap.remove("endTime");
			taskInMap.remove("beginTime");
			num = patientTaskDao.selectCount(taskInMap);
			// 如果没有任务信息进入下一次循环
			if (CollectionUtils.isEmpty(ptVoList)) {
				continue;
			}
			logger.info("11111111111111111111111" + ptVoList.size());
			// 查询随访方案任务内容入参
			PatientTask ptTaskVo = ptVoList.get(0);
			taskId = ptTaskVo.getId();
			taskInMap.clear();
			taskInMap.put("taskId", taskId);
			taskInMap.put("contTemplType", type);// 问卷模板类型

			// 查询随访方案任务内容
			List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(taskInMap);

			// 有任务信息
			if (!CollectionUtils.isEmpty(ptcList)) {
				// 查询是否填写了问卷入参
				Map<String, Object> valMapIn = new HashMap<String, Object>();
				valMapIn.put("taskId", taskId);
				valMapIn.put("contDataTemplType", type);

				// 查询患者内容详情表
				List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(valMapIn);

				// 已填写过问卷，过滤掉，继续下一次循环
				if (!CollectionUtils.isEmpty(ptTaskConList)) {
					logger.info("2222222222222222222" + ptVoList.size());
					continue;
				}

				// 查询问卷模板入参
				PatientTaskContent ptcVo = ptcList.get(0);
				Map<String, Object> contVerMap = new HashMap<String, Object>();
				contVerMap.put("id", ptcVo.getTemplVersionid());

				// 查询问卷模板
				List<Map<String, Object>> ctvList = contentTemplDao.selectTemplInfoByTemplVersionId(contVerMap);

				// 没有问卷模板直接跳过
				if (CollectionUtils.isEmpty(ctvList)) {
					logger.info("33333333333333" + ptVoList.size());
					continue;
				}

				Map<String, Object> outCtvMap = ctvList.get(0);
				totalNum++;// 还需要填写的随访问卷次数
				logger.info("totalNum!!!!!!!!!!!" + totalNum);
				// 接收一个task任务信息
				Map<String, Object> taskMap = new HashMap<String, Object>();
				taskMap.put("ptTaskId", taskId);
				taskMap.put("seqNo", ptTaskVo.getSeqNo());
				taskMap.put("patientId", patientId);
				taskMap.put("ptSchemeId", ptTaskVo.getPtSchemeid());
				taskMap.put("followQueueId", ptTaskVo.getQueueId());
				taskMap.put("quesType", type);
				taskMap.put("templName", outCtvMap.get("templName"));// 问卷名字
				// 随访系统科室id
				taskMap.put("departmentId", followDeptId);
				retList.add(t, taskMap);
				String executeAddress = "";
				String executeTime = "";
				if (!StringUtils.isEmpty(ptTaskVo.getExecuteAddress())) {
					executeAddress = ptTaskVo.getExecuteAddress();
					executeTime = ptTaskVo.getExecuteTime();
					addressList.add(t, executeAddress);
				}

				// 若执行时间不为空，则判断当前时间是否小于执行时间，小于则使用，否则不使用;
				String nowDate = DateUtil.getCurrDate2();
				if (!StringUtils.isEmpty(executeTime)) {
					if (nowDate.compareTo(executeTime) > 0) {
						executeTime = "";
					}
				}

				// 重新查询排班（从今天开始），获取具体时间段(上午，下午或晚上等）
				Map<String, Object> scheMapIn = new HashMap<String, Object>();
				scheMapIn.put("deptId", followDeptId);
				scheMapIn.put("beginTime", DateUtil.getCurrDate2());
				scheMapIn.put("endTime", ptTaskVo.getEndTime());
				List<String> scheDateList = PatientInfoHisService.listOutPtRandSchedule(scheMapIn);
				if (CollectionUtils.isEmpty(scheDateList)) {
					retOutMap.put("informMsg", "截止到当前任务过期时间，科室无随访排班!");
				}

				// 将executeTime作为首选，若在门诊排班日期内
				if (!StringUtils.isEmpty(executeTime)) {
					int kt = 0;
					int ksize = scheDateList.size();
					for (kt = 0; kt < ksize; kt++) {
						String nextDate = scheDateList.get(kt);
						String[] nextDateArr = nextDate.split(Constants.COLON_SPLIT_STR);
						if (executeTime.equals(nextDateArr[0])) {
							executeTime = nextDate;
							dateList.add(t, nextDate);
							break;
						}
					}
					for (kt = 0; kt < ksize; kt++) {
						String nextDate = scheDateList.get(kt);
						if (executeTime.equals(nextDate)) {
							continue;
						}
						dateList.add(t, executeTime);
					}
				} else {
					dateList = scheDateList;
				}

			}
		}

		logger.info("2222222222!!!!!!!!!!!总次数：" + totalNum);
		// 如果有需要填写的问卷返回信息
		if (totalNum > 0) {
			retOutMap.put("remainNum", num);
			retOutMap.put("rows", retList);
			retOutMap.put("total", totalNum);
			retOutMap.put("dateList", dateList);
			retOutMap.put("addressList", addressList);
		}

		return retOutMap;
	}

	// 预约通用接口接口
	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<Map<String, Object>> orderCommonInfo(Map<String, Object> qryPqsMap, Map<String, Object> MapIn, int i)
			throws Exception {
		logger.info("orderCommonInfo()~~~~~~~~：" + qryPqsMap.toString());
		qryPqsMap.put("type", "0");
		Jedis jedis = null;
		HashMap<String, Object> map = new HashMap<String, Object>(MapIn);
		Map<String, Object> mapInfo = new HashMap<String, Object>(qryPqsMap);
		Map<String, Object> mapOut = new HashMap<String, Object>();
		String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
		Date date = new Date();
		String dateTime = DateUtil.getDate_8(date);
		String dateNow = DateUtil.getDateHm();// 获取当前时间 yyyy-mm-dd hh:mm

		String argmsg = "";// 医院出参
		// 解析返回的xml字符串，转化成list
		List<Map<String, Object>> listone = new ArrayList<Map<String, Object>>();
		// 需要通过用户id和队列id查询用户预约信息
		MapIn.put("userId", qryPqsMap.get("platform_key"));
		List<PatientQueueScheme> Scheme = new ArrayList<PatientQueueScheme>();
		if (i == 3 || i == 4) {
			Scheme = patientQueueSchemeDao.selectPatientByCondition(MapIn);
		}

		// i代表当前调用的是什么接口 0：获取预约科室列表；1：获取预约专家信息；2：获取预约资源模板；3：提交预约；4：取消预约获取；
		switch (i) {
		case 0:
			qryPqsMap.put("code", Constants.STRING_SERVICECODE_A02Y007O);
			mapInfo.put("id", Constants.STRING_SERVICECODE_A02Y007O);
			mapInfo.put("templ_name", "预约信息");
			mapInfo.put("create_time", updateTime);
			mapInfo.put("bak2", "");
			mapInfo.put("bak3", "");
			mapOut = patientDao.selectoutTableInfo(mapInfo);
			// 先不加时间查询条件
			mapInfo.put("bak1", dateTime);
			if (mapOut != null && mapOut.size() > 0) {
				if (mapOut.get("bak1").equals(dateTime)) {
					// System.out.println("mapOut111111111111111111");
					argmsg = mapOut.get("template").toString();
					listone = ToolUtils.FormatXml(argmsg);
				} else {
					/*
					 * System.out.println("mapOut2222222222222222222"); argmsg =
					 * "<?xml version=\"1.0\" encoding=\"gbk\"?>" + "<rows>" +
					 * "<row dept_code=\"1001\" dept_name=\"新生儿科\" dept_describe=\"新生儿科创建于20世纪60年代初期，是国内首建的独立的新生儿科，并逐步建立和完善了新生儿重症监护室（NICU)，在国内外均享有一定声誉。从建院初期开始，已完成了近三十万新生儿的救治和护理工作。为规范NICU的日常工作，明确职责，有着一套完善的管理制度，同时积极采纳国内外先进的管理模式，运用新技术、新方法，旨在进一步提高我科危重及疑难患儿的诊治水平及管理水平。\" "
					 * +
					 * "level=\"1\" parent_code=\"100\" parent_name=\"临床科室\" show_status=\"1\"  webyy_status=\"1\"/>"
					 * +
					 * "<row dept_code=\"1002\" dept_name=\"产 科\" dept_describe=\"中福会国际和平妇幼保健院围产科在上海及全国一直享有较高的临床和科研地位，设有门诊、产房、病房，保健院产科主要开展围产医学范畴内的医疗及保健，尤其擅长优生咨询，产前诊断，各种高危妊娠的筛查、监护及治疗，妊娠合并症及妊娠并发症的诊断与治疗，还率先将产科和新生儿科合并成立围产科，坚持产前、产时、产后一贯制服务模式，开展产前诊断、围产会诊、遗传优生、孕前优生、营养咨询与指导等多项专科特色门诊，并且在全市范围内首先推行一对一导乐全程陪伴分娩、镇痛分娩、家庭化分娩、母乳喂养指导、产前产后营养餐等服务，为孕产妇提供一流的就医环境和优质温馨的诊疗服务。自建院以来，在几代人的不懈努力下，年分娩人数一直居全市前列，60年来共有超过30万名婴儿在我院出生。近年来，保健院孕产妇的高危妊娠率占75%，危重病例抢救成功率达100%，围产儿死亡率为4‰，达到发达国家水平。\" "
					 * +
					 * "level=\"1\" parent_code=\"100\" parent_name=\"临床科室\" show_status=\"0\"  webyy_status=\"1\"/>"
					 * + "</rows>";
					 */

					argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", qryPqsMap);
					listone = ToolUtils.FormatXml(argmsg);
					mapInfo.put("template", argmsg);
					if (listone != null && listone.size() > 0) {
						patientDao.updateoutTableByid(mapInfo);
					}
				}

			} else {
				argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", qryPqsMap);
				/*
				 * argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?>" + "<rows>" +
				 * "<row dept_code=\"1001\" dept_name=\"新生儿科\" dept_describe=\"新生儿科创建于20世纪60年代初期，是国内首建的独立的新生儿科，并逐步建立和完善了新生儿重症监护室（NICU)，在国内外均享有一定声誉。从建院初期开始，已完成了近三十万新生儿的救治和护理工作。为规范NICU的日常工作，明确职责，有着一套完善的管理制度，同时积极采纳国内外先进的管理模式，运用新技术、新方法，旨在进一步提高我科危重及疑难患儿的诊治水平及管理水平。\" "
				 * +
				 * "level=\"1\" parent_code=\"100\" parent_name=\"临床科室\" show_status=\"1\"  webyy_status=\"1\"/>"
				 * +
				 * "<row dept_code=\"1002\" dept_name=\"产 科\" dept_describe=\"中福会国际和平妇幼保健院围产科在上海及全国一直享有较高的临床和科研地位，设有门诊、产房、病房，保健院产科主要开展围产医学范畴内的医疗及保健，尤其擅长优生咨询，产前诊断，各种高危妊娠的筛查、监护及治疗，妊娠合并症及妊娠并发症的诊断与治疗，还率先将产科和新生儿科合并成立围产科，坚持产前、产时、产后一贯制服务模式，开展产前诊断、围产会诊、遗传优生、孕前优生、营养咨询与指导等多项专科特色门诊，并且在全市范围内首先推行一对一导乐全程陪伴分娩、镇痛分娩、家庭化分娩、母乳喂养指导、产前产后营养餐等服务，为孕产妇提供一流的就医环境和优质温馨的诊疗服务。自建院以来，在几代人的不懈努力下，年分娩人数一直居全市前列，60年来共有超过30万名婴儿在我院出生。近年来，保健院孕产妇的高危妊娠率占75%，危重病例抢救成功率达100%，围产儿死亡率为4‰，达到发达国家水平。\" "
				 * +
				 * "level=\"1\" parent_code=\"100\" parent_name=\"临床科室\" show_status=\"0\"  webyy_status=\"1\"/>"
				 * + "</rows>";
				 */
				mapInfo.put("template", argmsg);
				listone = ToolUtils.FormatXml(argmsg);
				if (listone != null && listone.size() > 0) {
					patientDao.insertIntooutTableInfo(mapInfo);
				}
			}
			break;
		case 1:
			qryPqsMap.put("code", Constants.STRING_SERVICECODE_A02Y008O);
			mapInfo.put("id", Constants.STRING_SERVICECODE_A02Y008O);
			mapInfo.put("templ_name", "预约信息");
			mapInfo.put("create_time", updateTime);
			mapInfo.put("bak3", "");
			mapInfo.put("bak2", qryPqsMap.get("dept_code"));
			mapOut = patientDao.selectoutTableInfo(mapInfo);
			// 先不加时间查询条件
			mapInfo.put("bak1", dateTime);
			if (mapOut != null && mapOut.size() > 0) {
				if (mapOut.get("bak1").equals(dateTime)) {
					argmsg = mapOut.get("template").toString();
					listone = ToolUtils.FormatXml(argmsg);
				} else {
					/*
					 * argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?>" + "<rows>" +
					 * "<row dept_code=\"1001\" dept_name=\"新生儿科\" expert_id=\"573\" expert_name=\"施婴婴\" expert_describe=\"新生儿科及儿童保健科主任，毕业于上海交大医学院儿科系。擅长于新生儿及婴儿常见疾病的诊治，婴儿喂养及食物过敏的指导，围产期溶血症的处理\" expert_title=\"主任医师\" begood=\"新生儿及婴儿常见疾病的诊治\"  outtime=\"2017-07-24 ：星期一下午\" docstate=\"0\" />"
					 * +
					 * "<row dept_code=\"1001\" dept_name=\"新生儿科\" expert_id=\"141\" expert_name=\"刘志伟\" expert_describe=\"医学博士、主任医师、硕士生导师。现任上海市儿科学会新生儿学组副组长、上海市围产医学会委员兼秘书、中国医师协会新生儿分会委员、上海市生物医学工程学会新生儿分会副主任委员、《临床儿科杂志》编委。从事围产新生儿临床20年，曾赴美国佛罗里达大学附属SHANDS医院和辛辛那提儿童医学中心留学深造，具有扎实的专业基础理论和丰富的临床经验。擅长新生儿疾病的诊断和治疗、早产儿随访以及儿童常见病的诊治。\" expert_title=\"主任医师\" begood=\"新生儿疾病的诊断和治疗、早产儿随访以及儿童常见病\"  outtime=\"2017-07-24 ：星期一下午\" docstate=\"0\" />"
					 * +
					 * "<row dept_code=\"1001\" dept_name=\"新生儿科\" expert_id=\"153\" expert_name=\"沈月华\" expert_describe=\"毕业于上海第二医学院儿科系，一直从事儿科临床工作。具有极丰富的临床经验。主要擅长婴儿常见疾病的诊治，婴幼儿保健的指导，优生优育咨询，及药物对胎儿的影响。\" expert_title=\"主任医师\" begood=\"婴儿常见疾病的诊治，婴幼儿保健的指导，优生优育咨询，药物对胎儿的影\"  outtime=\"2017-07-24 ：星期一下午\" docstate=\"0\" />"
					 * + "</rows>";
					 */
					argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", qryPqsMap);
					listone = ToolUtils.FormatXml(argmsg);
					if (listone != null && listone.size() > 0) {
						mapInfo.put("template", argmsg);
						patientDao.updateoutTableByid(mapInfo);
					}
				}

			} else {
				/*
				 * argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?>" + "<rows>" +
				 * "<row dept_code=\"1001\" dept_name=\"新生儿科\" expert_id=\"573\" expert_name=\"施婴婴\" expert_describe=\"新生儿科及儿童保健科主任，毕业于上海交大医学院儿科系。擅长于新生儿及婴儿常见疾病的诊治，婴儿喂养及食物过敏的指导，围产期溶血症的处理\" expert_title=\"主任医师\" begood=\"新生儿及婴儿常见疾病的诊治\"  outtime=\"2017-07-24 ：星期一下午\" docstate=\"0\" />"
				 * +
				 * "<row dept_code=\"1001\" dept_name=\"新生儿科\" expert_id=\"141\" expert_name=\"刘志伟\" expert_describe=\"医学博士、主任医师、硕士生导师。现任上海市儿科学会新生儿学组副组长、上海市围产医学会委员兼秘书、中国医师协会新生儿分会委员、上海市生物医学工程学会新生儿分会副主任委员、《临床儿科杂志》编委。从事围产新生儿临床20年，曾赴美国佛罗里达大学附属SHANDS医院和辛辛那提儿童医学中心留学深造，具有扎实的专业基础理论和丰富的临床经验。擅长新生儿疾病的诊断和治疗、早产儿随访以及儿童常见病的诊治。\" expert_title=\"主任医师\" begood=\"新生儿疾病的诊断和治疗、早产儿随访以及儿童常见病\"  outtime=\"2017-07-24 ：星期一下午\" docstate=\"0\" />"
				 * +
				 * "<row dept_code=\"1001\" dept_name=\"新生儿科\" expert_id=\"153\" expert_name=\"沈月华\" expert_describe=\"毕业于上海第二医学院儿科系，一直从事儿科临床工作。具有极丰富的临床经验。主要擅长婴儿常见疾病的诊治，婴幼儿保健的指导，优生优育咨询，及药物对胎儿的影响。\" expert_title=\"主任医师\" begood=\"婴儿常见疾病的诊治，婴幼儿保健的指导，优生优育咨询，药物对胎儿的影\"  outtime=\"2017-07-24 ：星期一下午\" docstate=\"0\" />"
				 * + "</rows>";
				 */
				argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", qryPqsMap);
				listone = ToolUtils.FormatXml(argmsg);
				if (listone != null && listone.size() > 0) {
					mapInfo.put("template", argmsg);
					patientDao.insertIntooutTableInfo(mapInfo);
				}
			}
			break;
		case 2:
			// 由于医院系统刷新接口时间为30分钟，所以设30分钟缓存
			qryPqsMap.put("code", Constants.STRING_SERVICECODE_A02Y002O);
			if (qryPqsMap.get("flag").equals("0")) {
				try {
					String redisStr = Constants.STRING_SERVICECODE_A02Y002O
							+ qryPqsMap.get("dept_code").toString().trim() + qryPqsMap.get("endate").toString().trim();
					logger.info("redisStr 00 :" + redisStr);
					jedis = jedisPool.getResource();
					// jedis.del(redisStr);
					argmsg = jedis.get(redisStr);
					if (argmsg == null) {
						argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", qryPqsMap);
						// argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row
						// deptl1code=\"09\" deptl2code=\"0104013\" deptl2name=\"儿保康复\" doctorid=\"\"
						// doctorname=\"\" partcode=\"04\" date=\"2017-07-31\" resourcesum=\"145\"
						// /><row deptl1code=\"09\" deptl2code=\"0104013\" deptl2name=\"儿保康复\"
						// doctorid=\"400\" doctorname=\"余文\" partcode=\"01\" date=\"2017-07-27\"
						// resourcesum=\"0\" /><row deptl1code=\"09\" deptl2code=\"0104013\"
						// deptl2name=\"儿保康复\" doctorid=\"475\" doctorname=\"祝丹\" partcode=\"02\"
						// date=\"2017-07-31\" resourcesum=\"0\" /></rows>";
						logger.info("redisStr 00sss :" + redisStr);
						listone = ToolUtils.FormatXml(argmsg);
						JSONArray jsonArray = JSONArray.fromObject(listone);
						jedis.set(redisStr, jsonArray.toString());
						jedis.expire(redisStr, 10800);
					} else {
						JSONArray array = JSONArray.fromObject(argmsg);
						listone = JSONArray.toList(array, new HashMap<String, Object>(), new JsonConfig());
					}
				} catch (JedisConnectionException jex) {
					logger.error("redis连接异常..." + jex.getMessage());
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
				} finally {
					if (null != jedis) {
						try {
							jedis.close();
							logger.warn("close redis connection...");
						} catch (Exception ex) {
							ex.printStackTrace();
							throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
									"Redis缓存关闭失败!"));
						}
					}
				}
			} else {
				String expertCode = qryPqsMap.get("expert_code").toString();
				String partcode = qryPqsMap.get("partcode").toString();
				String redisStr = partcode + expertCode + qryPqsMap.get("endate").toString();
				String datefor = DateUtil.getDate_8(new Date());
				String redisStr1 = datefor + "argmsg";
				String redisStr0 = Constants.STRING_SERVICECODE_A02Y002O + qryPqsMap.get("dept_code").toString().trim()
						+ qryPqsMap.get("endate").toString().trim();
				logger.info("redisStr参数：" + redisStr);
				try {
					jedis = jedisPool.getResource();
					argmsg = jedis.get(redisStr);
					if (argmsg == null) {
						argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", qryPqsMap);
						// argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row
						// templateid=\"2260036\" comcode=\"020059\" deptl1code=\"09\"
						// deptl2code=\"0104013\" deptl2name=\"儿保康复\" registertype=\"1\"
						// doctorid=\"475\" doctorname=\"吕志伟\" date=\"2017-07-31\" timestart=\"13:30\"
						// timeend=\"14:30\" cancelled=\"FALSE\" canceltime=\"\" registerfee=\"300.00\"
						// out_period=\"1\" partcode=\"02\" num=\"121212\" Regtype=\"T\"
						// Expert_degree=\"4\" /><row templateid=\"2260037\" comcode=\"020059\"
						// deptl1code=\"09\" deptl2code=\"0104013\" deptl2name=\"儿保康复\"
						// registertype=\"1\" doctorid=\"475\" doctorname=\"吕志伟\" date=\"2017-07-31\"
						// timestart=\"14:30\" timeend=\"15:30\" cancelled=\"FALSE\" canceltime=\"\"
						// registerfee=\"300.00\" out_period=\"1\" partcode=\"02\" num=\"12\"
						// Regtype=\"T\" Expert_degree=\"4\" /><row templateid=\"2260038\"
						// comcode=\"020059\" deptl1code=\"09\" deptl2code=\"0104013\"
						// deptl2name=\"儿保康复\" registertype=\"1\" doctorid=\"475\" doctorname=\"吕志伟\"
						// date=\"2017-07-31\" timestart=\"15:30\" timeend=\"16:30\" cancelled=\"FALSE\"
						// canceltime=\"\" registerfee=\"300.00\" out_period=\"1\" partcode=\"02\"
						// num=\"0\" Regtype=\"T\" Expert_degree=\"4\" /></rows>";
						// argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row
						// templateid=\"2260036\" comcode=\"020059\" deptl1code=\"09\"
						// deptl2code=\"0104013\" deptl2name=\"儿保康复\" registertype=\"1\" doctorid=\"\"
						// doctorname=\"\" date=\"2017-07-31\" timestart=\"13:30\" timeend=\"14:30\"
						// cancelled=\"FALSE\" canceltime=\"\" registerfee=\"300.00\" out_period=\"1\"
						// partcode=\"04\" num=\"2500\" Regtype=\"T\" Expert_degree=\"4\" /><row
						// templateid=\"2260037\" comcode=\"020059\" deptl1code=\"09\"
						// deptl2code=\"0104013\" deptl2name=\"儿保康复\" registertype=\"1\" doctorid=\"\"
						// doctorname=\"\" date=\"2017-07-31\" timestart=\"14:30\" timeend=\"15:30\"
						// cancelled=\"FALSE\" canceltime=\"\" registerfee=\"300.00\" out_period=\"1\"
						// partcode=\"04\" num=\"12\" Regtype=\"T\" Expert_degree=\"4\" /><row
						// templateid=\"2260038\" comcode=\"020059\" deptl1code=\"09\"
						// deptl2code=\"0104013\" deptl2name=\"儿保康复\" registertype=\"1\" doctorid=\"\"
						// doctorname=\"\" date=\"2017-07-31\" timestart=\"15:30\" timeend=\"16:30\"
						// cancelled=\"FALSE\" canceltime=\"\" registerfee=\"300.00\" out_period=\"1\"
						// partcode=\"04\" num=\"0\" Regtype=\"T\" Expert_degree=\"4\" /></rows>";
						jedis.set(redisStr, argmsg);
						jedis.set(redisStr1, argmsg);
						// System.out.println("redisStr111111:"+redisStr1);
						jedis.expire(redisStr, 60);
						jedis.expire(redisStr1, 60);
					}
				} catch (JedisConnectionException jex) {
					logger.error("redis连接异常..." + jex.getMessage());
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
				} finally {
					if (null != jedis) {
						try {
							jedis.close();
							logger.warn("close redis connection...");
						} catch (Exception ex) {
							ex.printStackTrace();
							throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
									"Redis缓存关闭失败!"));
						}
					}
				}
				// argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row
				// deptl1code=\"09\" deptl2code=\"0104013\" deptl2name=\"儿保康复\" doctorid=\"\"
				// doctorname=\"\" partcode=\"04\" date=\"2017-07-27\" resourcesum=\"145\"
				// /><row deptl1code=\"09\" deptl2code=\"0104013\" deptl2name=\"儿保康复\"
				// doctorid=\"400\" doctorname=\"余文\" partcode=\"01\" date=\"2017-07-27\"
				// resourcesum=\"0\" /><row deptl1code=\"09\" deptl2code=\"0104013\"
				// deptl2name=\"儿保康复\" doctorid=\"442\" doctorname=\"祝丹\" partcode=\"01\"
				// date=\"2017-07-27\" resourcesum=\"0\" /></rows>";
				// argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row
				// templateid=\"2260036\" comcode=\"020059\" deptl1code=\"09\"
				// deptl2code=\"0104013\" deptl2name=\"儿保康复\" registertype=\"1\"
				// doctorid=\"475\" doctorname=\"吕志伟\" date=\"2017-07-31\" timestart=\"13:30\"
				// timeend=\"14:30\" cancelled=\"FALSE\" canceltime=\"\" registerfee=\"300.00\"
				// out_period=\"1\" partcode=\"02\" num=\"0\" Regtype=\"T\" Expert_degree=\"4\"
				// /><row templateid=\"2260037\" comcode=\"020059\" deptl1code=\"09\"
				// deptl2code=\"0104013\" deptl2name=\"儿保康复\" registertype=\"1\"
				// doctorid=\"475\" doctorname=\"吕志伟\" date=\"2017-07-31\" timestart=\"14:30\"
				// timeend=\"15:30\" cancelled=\"FALSE\" canceltime=\"\" registerfee=\"300.00\"
				// out_period=\"1\" partcode=\"02\" num=\"0\" Regtype=\"T\" Expert_degree=\"4\"
				// /><row templateid=\"2260038\" comcode=\"020059\" deptl1code=\"09\"
				// deptl2code=\"0104013\" deptl2name=\"儿保康复\" registertype=\"1\"
				// doctorid=\"475\" doctorname=\"吕志伟\" date=\"2017-07-31\" timestart=\"15:30\"
				// timeend=\"16:30\" cancelled=\"FALSE\" canceltime=\"\" registerfee=\"300.00\"
				// out_period=\"1\" partcode=\"02\" num=\"0\" Regtype=\"T\" Expert_degree=\"4\"
				// /></rows>";
				listone = ToolUtils.FormatXml(argmsg);
				if (listone != null && listone.size() > 0) {
					try {
						jedis = jedisPool.getResource();
						String time = listone.get(0).get("date").toString();
						String code = listone.get(0).get("partcode").toString();
						String doctorid = listone.get(0).get("doctorid").toString();
						int totle = 0;// 所有的可预约次数
						String str = jedis.get(redisStr0);// 从redis中取得医生列表中的数据，用于刷新缓存数据
						if (str != null) {

							for (int b = 0; b < listone.size(); b++) {
								// 获得所有的预约次数
								totle = totle + Integer.parseInt(String.valueOf(listone.get(b).get("num")));
							}
							// 将str处理成list
							List<Map<String, Object>> list = JSONArray.fromObject(str);
							int a = 0;
							int length = list.size();// list长度
							// 循环处理医生列表信息
							if (list != null && length > 0) {
								for (; a < length; a++) {
									Map<String, Object> mapinfo = list.get(a);
									// 如果有医生id则用医生id处理
									if (!StringUtils.isEmpty(mapinfo.get("doctorid"))) {
										// 判断时间和门诊类型是否匹配
										if (time.equals(mapinfo.get("date").toString().trim())
												&& code.equals(mapinfo.get("partcode").toString().trim())
												&& doctorid.equals(mapinfo.get("doctorid").toString().trim())) {
											mapinfo.put("resourcesum", totle + "");
											// 替换医列表中的预约总数
											list.set(a, mapinfo);
										}
									} else {
										// 判断时间和门诊类型是否匹配
										if (time.equals(mapinfo.get("date").toString().trim())
												&& code.equals(mapinfo.get("partcode").toString().trim())) {
											mapinfo.put("resourcesum", totle + "");
											// 替换医列表中的预约总数
											list.set(a, mapinfo);
										}
									}
								}
								jedis.set(redisStr0, JSONArray.fromObject(list).toString());// 将更新后的医生列表信息放入缓存
								jedis.expire(redisStr0, 10800);
							}
						}
					} catch (JedisConnectionException jex) {
						logger.error("redis连接异常..." + jex.getMessage());
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
					} finally {
						if (null != jedis) {
							try {
								jedis.close();
								logger.warn("close redis connection...");
							} catch (Exception ex) {
								ex.printStackTrace();
								throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
										"Redis缓存关闭失败!"));
							}
						}
					}
					String hour = DateUtil.getMh();// 获取时间 格式：HH:mm
					int li = 0;
					int length = listone.size();
					int big = hour.compareTo(listone.get(li).get("timeend").toString().trim());
					for (; li < length; li++) {
						if (big > 0) {
							listone.get(li).put("lose", "0");
						}
					}
				} else {
					Map<String, Object> maperror = new HashMap<String, Object>();
					listone.clear();
					maperror.put("errorCode", "0012");
					listone.add(maperror);
				}

			}

			break;
		case 3:
			qryPqsMap.put("code", Constants.STRING_SERVICECODE_A02Y003O);

			/*
			 * argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?>" + "<rows>" +
			 * "<row issucess=\"1\" message=\"预约成功\" reservationid=\"8897482\" />" +
			 * "</rows>";
			 */

			argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", qryPqsMap);
			listone = ToolUtils.FormatXml(argmsg);
			break;
		case 4:
			qryPqsMap.put("code", Constants.STRING_SERVICECODE_A02Y004O);
			if (StringUtils.isEmpty(qryPqsMap.get("reservationid"))) {
				if (Scheme.size() > 0) {
					String reservationId = Scheme.get(0).getReservationId();
					String dateOrder = "";
					int bigOne = -1;
					if (StringUtils.isEmpty(Scheme.get(0).getDate())) {
					} else {
						dateOrder = Scheme.get(0).getDate();
						bigOne = dateOrder.compareTo(dateNow);
					}
					if (StringUtils.isEmpty(reservationId) || bigOne < 0) {
						throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST,
								"没有查询到当前用户预约信息！");
					} else {
						qryPqsMap.put("reservationId", reservationId);
					}
				} else {
					throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_QUEUE_NOT_EXIST, "没有查询到当前用户预约信息！");
				}
			}
			argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", qryPqsMap);

			/*
			 * argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?>" + "<rows>" +
			 * "<row issucess=\"1\" message=\"操作成功\"/>" + "</rows>";
			 */

			listone = ToolUtils.FormatXml(argmsg);
			break;
		}

		logger.info("qryPqsMap@@@" + qryPqsMap.toString());
		// 调用远程接口
		logger.info("qryPqsMaspsssssss@@@" + argmsg.toString());
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		if (listone != null && listone.size() > 0) {
			if (i == 3) {
				String Date = MapIn.get("date").toString().trim() + " " + MapIn.get("endtime").toString().trim();
				logger.info("Date format :" + Date);
				map.put("updateTime", updateTime);
				map.put("updateAccept", updateAccept);
				map.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
				map.put("isSuccess", listone.get(0).get("issucess"));
				map.put("message", listone.get(0).get("message"));
				map.put("reservationId", listone.get(0).get("reservationid"));
				map.put("platform_key", MapIn.get("userId"));
				map.put("date", Date);
				if ("预约成功".equals((String) listone.get(0).get("message"))) {
					try {
						if (jedis != null) {
							jedis.close();
						}
						jedis = jedisPool.getResource();
						String datefor = DateUtil.getDate_8(new Date());
						String redisStr1 = datefor + "argmsg";
						// System.out.println("redisStr1"+redisStr1);
						String argmsgs = jedis.get(redisStr1);
						if (argmsgs != null) {
							String templateid = qryPqsMap.get("templateid").toString();
							String datenow = MapIn.get("date").toString();
							String Dept = "";
							String time = "";
							String code = "";
							String doctorid = "";
							List<Map<String, Object>> listchange = ToolUtils.FormatXml(argmsgs);
							if (listchange != null && listchange.size() > 0) {
								for (int d = 0; d < listchange.size(); d++) {
									if (templateid.equals(listchange.get(d).get("templateid"))
											&& datenow.equals(listchange.get(d).get("date"))) {
										Dept = listchange.get(d).get("deptl2code").toString();
										code = listchange.get(d).get("partcode").toString();
										time = listchange.get(d).get("date").toString();
										doctorid = listchange.get(d).get("doctorid").toString();
									}
								}
							}
							String redisStr0 = Constants.STRING_SERVICECODE_A02Y002O + Dept.trim() + datenow.trim();
							String argmsgss = jedis.get(redisStr0);
							// 将str处理成list
							if (argmsgss != null) {
								JSONArray array = JSONArray.fromObject(argmsgss);
								List<Map<String, Object>> list = JSONArray.toList(array, new HashMap<String, Object>(),
										new JsonConfig());
								int j = 0;
								int length = list.size();// list长度
								// 循环处理医生列表信息
								if (list != null && length > 0) {
									int totle = 0;
									for (; j < length; j++) {
										Map<String, Object> mapinfo = list.get(j);
										// 如果有医生id则用医生id处理
										if (!StringUtils.isEmpty(mapinfo.get("doctorid"))) {
											// 判断时间和门诊类型是否匹配
											if (time.equals(mapinfo.get("date").toString().trim())
													&& code.equals(mapinfo.get("partcode").toString().trim())
													&& doctorid.equals(mapinfo.get("doctorid").toString().trim())) {
												totle = Integer.parseInt(mapinfo.get("resourcesum").toString().trim());
												if (totle > 0) {
													mapinfo.put("resourcesum", totle - 1 + "");
												}
												// System.out.println("mapinfo"+mapinfo.toString());
												// 替换医列表中的预约总数
												list.set(j, mapinfo);
											}
										} else {
											// 判断时间和门诊类型是否匹配
											if (time.equals(mapinfo.get("date").toString().trim())
													&& code.equals(mapinfo.get("partcode").toString().trim())) {
												totle = Integer.parseInt(mapinfo.get("resourcesum").toString().trim());
												if (totle > 0) {
													mapinfo.put("resourcesum", totle - 1 + "");
													// System.out.println("mapinfo111"+mapinfo.toString());
												}
												// 替换医列表中的预约总数
												list.set(j, mapinfo);
											}
										}
									}
									jedis.set(redisStr0, JSONArray.fromObject(list).toString());// 将更新后的医生列表信息放入缓存
									jedis.expire(redisStr0, 10800);
								}
							}
						}
					} catch (JedisConnectionException jex) {
						logger.error("redis连接异常..." + jex.getMessage());
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
					} finally {
						if (null != jedis) {
							try {
								jedis.close();
								logger.warn("close redis connection...");
							} catch (Exception ex) {
								ex.printStackTrace();
								throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
										"Redis缓存关闭失败!"));
							}
						}
					}
					patientqueryCardDAO.PatientQueueSchemeHis(map);
					patientqueryCardDAO.updateOrderByuserId(map);
				}
			} else if (i == 4) {
				// String datefor = DateUtil.getDate_8(new Date());
				map.put("updateTime", updateTime);
				map.put("updateAccept", updateAccept);
				map.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
				map.put("isSuccess", listone.get(0).get("issucess"));
				map.put("message", listone.get(0).get("message"));
				map.put("reservationId", "");
				map.put("date", "");
				map.put("platform_key", MapIn.get("platform_key"));
				String redisStr0 = Constants.STRING_SERVICECODE_A02Y002O + "0104013" + "2017-08-12";
				// String redisStr0 =
				// Constants.STRING_SERVICECODE_A02Y002O+"0104013"+datefor;
				System.out.println("listone    ddd: " + listone.get(0).get("message").toString().trim());
				if ("操作成功".equals((String) listone.get(0).get("message"))
						|| "操作成功".equals((String) listone.get(0).get("issucess"))) {
					try {
						if (jedis != null) {
							jedis.close();
						}
						jedis = jedisPool.getResource();
						String argmsgss = jedis.get(redisStr0);
						if (argmsgss != null) {
							JSONArray array = JSONArray.fromObject(argmsgss);
							List<Map<String, Object>> list = JSONArray.toList(array, new HashMap<String, Object>(),
									new JsonConfig());
							int j = 0;
							int length = list.size();// list长度
							// 循环处理医生列表信息
							if (list != null && length > 0) {
								int totle = 0;
								for (; j < length; j++) {
									Map<String, Object> mapinfo = list.get(j);
									// 判断时间和门诊类型是否匹配
									totle = Integer.parseInt(mapinfo.get("resourcesum").toString().trim());
									if (totle > 0) {
										mapinfo.put("resourcesum", totle + 1 + "");
									}
									// System.out.println("mapinfo"+mapinfo.toString());
									// 替换医列表中的预约总数
									list.set(j, mapinfo);
								}
								jedis.set(redisStr0, JSONArray.fromObject(list).toString());// 将更新后的医生列表信息放入缓存
								jedis.expire(redisStr0, 360);
							}
						}
					} catch (JedisConnectionException jex) {
						logger.error("redis连接异常..." + jex.getMessage());
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
					} finally {
						if (null != jedis) {
							try {
								jedis.close();
								logger.warn("close redis connection...");
							} catch (Exception ex) {
								ex.printStackTrace();
								throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
										"Redis缓存关闭失败!"));
							}
						}
					}
					patientqueryCardDAO.PatientQueueSchemeHis(map);
					patientqueryCardDAO.updateOrderByuserId(map);
				}
			}
		}
		logger.info("listone@@@" + listone.toString());
		return listone;
	}

	// list根据时间排序
	public class TestComparator implements Comparator<Map<String, Object>> {

		@Override
		public int compare(Map<String, Object> o1, Map<String, Object> o2) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = null;
			Date d2 = null;
			try {
				d1 = format.parse(o1.get("opTime").toString().trim());
				d2 = format.parse(o2.get("opTime").toString().trim());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (d1.before(d2)) {
				return 1;
			} else if (d1.after(d2)) {
				return -1;
			} else {
				return 0;
			}
		}

	}

	/*
	 * @author wuyz
	 *
	 * @deprecated 更新用户实例化任务id接口
	 *
	 * @date 2017年07月20
	 *
	 */
	@Override
	@Transactional
	public Map<String, Object> UpdateTaskInfo(HashMap<String, Object> servParamMap) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		// 操作类型
		String opType = servParamMap.get("opType").toString();
		// 查询当前任务id查询信息
		List<PatientTask> list = patientTaskDao.selectById(servParamMap);
		PatientTask pat = null;
		if (CollectionUtils.isEmpty(list)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_TASK_NOT_EXIST, "未查询当前用户任务信息！"));
		} else {
			pat = list.get(0);
		}

		String taskStatus = pat.getTaskStatus();// 当前任务的状态 0：任务未开始 ，1：任务已完成 ，
												// 2：任务已过期（未完成）
		String ptSchemeId = pat.getPtSchemeid();
		String userId = pat.getUserId();
		// 更新任务状态
		if (opType.equals(Constants.STRING_UPDATE_STAYUS)) {
			// 完成时间只能是今天或今天时间之前
			Date date1 = DateUtil.getDate(servParamMap.get("finishDate").toString());
			String dateNow = DateUtil.getCurrDate2();
			Date date2 = DateUtil.getDate(dateNow);// 当前时间
			int big = date1.compareTo(date2);
			logger.info("big  大小  :" + big);
			if (big > 0) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_TASK_NOT_EXIST, "结束时间不能大于当前时间！"));
			}

			if (Constants.PATIENT_TASK_STATUS_INIT.equals(taskStatus)) {
				servParamMap.put("taskStatus", Constants.PATIENT_TASK_STATUS_FINISH);
			}
			// 更新任务状态 pt_task_info
			logger.info("updatePatientTaskByIdOnApp  : " + servParamMap.toString());
			int upret = patientTaskDao.updatePatientTaskByIdOnApp(servParamMap);
			if (0 == upret) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_TASK_NOT_EXIST, "患者当前任务不存在！"));
			}
			// 入历史pt_task_info_his
			servParamMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
			logger.info("servParamMap  : " + servParamMap.toString());
			patientTaskDao.insertPatientTaskHisByIdApp(servParamMap);

		} else if (opType.equals(Constants.STRING_UPDATE_EXECUTE)) {
			// 更新随访时间
			servParamMap.put("taskStatus", Constants.PATIENT_TASK_STATUS_INIT);
			servParamMap.put("ptSchemeId", ptSchemeId);
			servParamMap.put("userId", userId);
			servParamMap.put("seqNoOrderAsc", "true");
			// 查询当前用户未完成任务信息
			List<PatientTask> lists = patientTaskDao.select(servParamMap);
			if (CollectionUtils.isEmpty(lists)) {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_TASK_NOT_EXIST, "当前用户无未完成任务信息！"));
			} else {
				// 当前用户有未完成任务信息，进行修改时间
				Date dateChange = DateUtil.getDate(servParamMap.get("ChangeDate").toString());// 更改的时间
				Date executeDay = DateUtil.getDate(lists.get(0).getExecuteTime());
				String calcType = "+";// 增加
				int days = DateUtil.daysBetween(executeDay, dateChange);// 计算两个时间差
				String executeTime = "";
				String beginTime = "";// 开始时间
				String endTime = "";// 结束时间
				// 循环修改任务时间
				for (int i = 0; i < lists.size(); i++) {
					PatientTask patask = lists.get(i);
					executeTime = DateUtil.calcDay2(patask.getExecuteTime(), calcType, days);// 增加时间
					beginTime = DateUtil.calcDay2(patask.getBeginTime(), calcType, days);
					endTime = DateUtil.calcDay2(patask.getEndTime(), calcType, days);
					servParamMap.put("taskId", patask.getId());
					servParamMap.put("updateTime", DateUtil.getTimeString(DateUtil.getSysDateA()));
					servParamMap.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
					// servParamMap.put("executeDay",
					// patask.getExecuteDay()+days);
					servParamMap.put("executeTime", executeTime);
					servParamMap.put("beginTime", beginTime);
					servParamMap.put("endTime", endTime);
					servParamMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
					// 入历史pt_task_info_his
					logger.info("servParamMapupdateType  : " + servParamMap.toString());
					patientTaskDao.insertPatientTaskHisByIdApp(servParamMap);
					// 更新pt_task_info
					patientTaskDao.updatePatientTaskByIdOnApp(servParamMap);
				}
			}

		}
		// 查询当前task并循环更新信息
		return map;
	}

	// 通过微信或者是服务号码和租户查询用户列表
	@Override
	public Map<String, Object> queryAllpatientList(Map<String, Object> paramMap) throws Exception {
		logger.info("queryAllpatientList : " + paramMap.toString());
		String openId = (String) paramMap.get("openId");
		String phoneNo = (String) paramMap.get("phoneNo");
		Map<String, Object> mapIn = new HashMap<String, Object>(paramMap);
		List<Map<String, Object>> listUser = new ArrayList<Map<String, Object>>();// 用户列表
		if (!StringUtils.isEmpty(openId) && StringUtils.isEmpty(phoneNo)) {
			/*
			 * logger.info("3333333333333333：" +mapIn.toString()); List<Map<String, Object>>
			 * list = patientqueryCardDAO.selectpatientidOrder(mapIn); if (list != null &&
			 * list.size() > 0) { for (int i = 0; i < list.size(); i++) {
			 * mapIn.put("phoneNo", list.get(i).get("phone_no")); mapIn.remove("openId");
			 * logger.info("paramMap"+" i "+mapIn.toString()); List<Map<String, Object>>
			 * lists = patientqueryCardDAO.selectpatientidQueue(mapIn);
			 * listUser.addAll(lists); } }
			 */
		} else {
			mapIn.remove("openId");
			List<Map<String, Object>> lists = patientqueryCardDAO.selectpatientidQueue(mapIn);
			if (CollectionUtils.isEmpty(lists)) {
				paramMap.put("paramValue", phoneNo);
				paramMap.put("paramName", Constants.SERVICE_NAME_FOR_EXTEND);
				List<PtUserextendInfo> ptextList = ptExtendDao.selectPtExtendInfo(paramMap);
				for (int j = 0; j < ptextList.size(); j++) {
					mapIn.put("phoneNo", ptextList.get(j).getRemark());
					List<Map<String, Object>> listone = patientqueryCardDAO.selectpatientid(mapIn);
					listUser.addAll(listone);
				}
			} else {
				listUser.addAll(lists);
			}

		}
		Map<String, Object> map = new HashMap<String, Object>();

		// 查询当前微信是否绑定了号码
		if (!StringUtils.isEmpty(openId)) {
			paramMap.remove("phoneNo");
		}
		logger.info("paramMap +＋:" + paramMap.toString());
		List<Map<String, Object>> wechatList = IConfCacheDAO.selectwechat(paramMap);
		logger.info("paramMap wewewewewe:" + wechatList.toString());
		paramMap.remove("openId");

		if (wechatList != null && wechatList.size() > 0) {
			map.put("bindPhoneNo", (String) wechatList.get(0).get("phone_no"));
			for (int i = 0; i < wechatList.size(); i++) {
				paramMap.put("phoneNo", (String) wechatList.get(i).get("phone_no"));
				List<Map<String, Object>> lists = patientqueryCardDAO.selectpatientidQueue(paramMap);
				listUser.addAll(lists);
			}
		} else {
			map.put("bindPhoneNo", "");
		}

		if (CollectionUtils.isEmpty(listUser) && !CollectionUtils.isEmpty(wechatList)) {
			mapIn.remove("phoneNo");
			mapIn.remove("openId");
			logger.info("mapIn  :  " + mapIn.toString());
			for (int i = 0; i < wechatList.size(); i++) {
				paramMap.put("paramValue", (String) wechatList.get(i).get("phone_no"));
				paramMap.put("paramName", Constants.SERVICE_NAME_FOR_EXTEND);
				List<PtUserextendInfo> ptextList = ptExtendDao.selectPtExtendInfo(paramMap);
				for (int j = 0; j < ptextList.size(); j++) {
					mapIn.put("phoneNo", ptextList.get(j).getRemark());
					List<Map<String, Object>> lists = patientqueryCardDAO.selectpatientid(mapIn);
					listUser.addAll(lists);
				}
			}
		}
		listUser = new ArrayList<Map<String, Object>>(new LinkedHashSet<>(listUser));
		map.put("userList", listUser);
		logger.info("ssssss: " + listUser.toString());
		map.put("openId", openId);
		return map;
	}

	// 修改用户号码业务逻辑处理,处理当前微信下所有用户的号码
	@Override
	@Transactional
	public Map<String, Object> ModifyUserPhoneNo(Map<String, Object> paramMap) throws Exception {
		Map<String, Object> mapIn = new HashMap<String, Object>(paramMap);
		logger.info("ModifyUserPhoneNo : " + paramMap.toString());
		String phoneNo = (String) paramMap.get("phoneNo");
		String openId = (String) paramMap.get("openId");
		String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		paramMap.put("updateTime", currTime);
		paramMap.put("updateAccept", updateAccept);

		// 更新微信绑定号码
		// IConfCacheDAO.updatewechat(paramMap);
		mapIn.remove("openId");
		mapIn.put("phoneNo", (String) mapIn.get("oldPhoneNo"));
		paramMap.remove("phoneNo");
		// 查询微信绑定的所有用户
		/*
		 * List<Patient> list = patientqueryCardDAO.selectpatientidByPhoneNo(mapIn); if
		 * (list != null && list.size() > 0) { for (int i = 0; i < list.size(); i++) {
		 */
		paramMap.put("phoneNo", (String) mapIn.get("oldPhoneNo"));
		// 通过号码查询当前队列用不信息
		paramMap.remove("openId");
		List<Patient> lists = patientqueryCardDAO.selectpatientidByPhoneNo(paramMap);
		for (int j = 0; j < lists.size(); j++) {
			Patient ptOut = lists.get(j);
			paramMap.put("currPhoneNum", ptOut.getPhoneNo());
			paramMap.put("userId", ptOut.getId());
			paramMap.put("phoneNo", phoneNo);
			paramMap.put("openId", openId);
			// 调用接口更新用户号码
			Map<String, Object> map = ModifyPhoneNo(paramMap);
			if (!org.apache.commons.lang.StringUtils.isBlank((String) map.get("newPhoneNo"))) {
				paramMap.put("Patient", ptOut);
				paramMap.put("newPhoneNo", (String) map.get("newPhoneNo"));
				// 如果改变了用户号码需要同步app

			}
		}
		/*
		 * } }
		 */
		return paramMap;
	}



	// 修改用户号码
	public Map<String, Object> ModifyPhoneNo(Map<String, Object> paramMap) throws Exception {
		logger.info("ModifyPhoneNo : " + paramMap.toString());
		Map<String, Object> userMapIn = new HashMap<String, Object>();
		String userId = (String) paramMap.get("userId");
		String updateTime = (String) paramMap.get("updateTime");
		String tenantId = (String)

				paramMap.get("tenantId");
		String updateAccept = (String) paramMap.get("updateAccept");
		String currPhoneNum = (String) paramMap.get("currPhoneNum");
		String phoneNo = (String) paramMap.get("phoneNo");
		String openId = (String) paramMap.get("openId");

		userMapIn.put("openId", openId);
		userMapIn.put("userId", userId);
		userMapIn.put("updateTime", updateTime);
		userMapIn.put("phoneNo", phoneNo);
		List<String> tenantIdList = new ArrayList<String>();
		tenantIdList.add(tenantId);
		tenantIdList.add(Constants.PT_USER_INFO_DEFAULT_TENANT_ID);
		userMapIn.put("tenantIdList", tenantIdList);
		// 修改当前租户id和默认0的基本信息
		patientDao.updatePatientInfoById(userMapIn);
		// 历史表记录
		Map<String, Object> userHisMap = new HashMap<String, Object>();
		userHisMap.put("userId", userId);
		userHisMap.put("updateTime", updateTime);
		userHisMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
		userHisMap.put("updateAccept", updateAccept);
		userHisMap.put("tenantIdList", tenantIdList);
		patientDao.savePatientHisInfo(userHisMap);

		Map<String, Object> queueMap = new HashMap<String, Object>();
		// 判断手机号码是否有变化，如果有变化，需要通知app侧调整，发送新的注册消息
		String newPhoneNo = (String) userMapIn.get("phoneNo");
		if (!StringUtils.isEmpty(newPhoneNo)) {
			if (!newPhoneNo.equals(currPhoneNum)) {
				// 设置标志位 ：同步流程放到最后
				queueMap.put("newPhoneNo", newPhoneNo);
			}
		}
		return queueMap;
	}

	// 获取推送患者清单，儿保门诊指导意见列表，儿保门诊指导意见详情
	@Override
	public Object pushCommonInfo(Map<String, Object> retMap, Map<String, Object> mapIn, int i)
			throws Exception {
		Object listone = new ArrayList<Map<String, Object>>();
		// 1:获取儿保门诊推送事项患者清单
		// 2:获取儿保门诊指导意见列表
		// 3:获取儿保门诊指导意见详情
		switch (i) {
		case 1:
			listone = callHispital(retMap, 3);
			break;
		case 2:
			listone = patientDao.selecttGuidance(retMap);
			break;
		case 3:
			listone = patientDao.selecttGuidance(retMap);
			break;
		}
		return listone;
	}

	// 调用医院接口和处理医院接口返回信息通用
	private List<Map<String, Object>> callHispital(Map<String, Object> retMap, int i) throws Exception {
		String argmsg = "";// 调用医院接口返回的信息
		argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", retMap);
		logger.info("调用医院接口出参患者清单：" + argmsg);
		/*if (i == 1) {
			argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row yjid=\"110\" jzrq=\"2017-09-12\"/></rows>";
		} else {
			argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row jynl=\"100\" wssd=\"维生素D\" gys=\"110\" fs=\"面包\" qt=\"无\" zd=\"正常\" cl=\"多喝水\" doctor=\"吴医生\"  yjdate=\"2017-09-12\"  /></rows>";
		}*/
		List<Map<String, Object>> listone = ToolUtils.FormatXml(argmsg);
		logger.info("转化后的list：" + listone.toString());
		return listone;
	}

	// 查询用户信息和队列实例信息
	private List<Map<String, Object>> getUserQueueInfo(Map<String, Object> retMap) throws Exception {
		retMap.put("userStatus", "1");
		List<Map<String, Object>> listone = patientDao.listPtArchInfoByCondition(retMap);
		if (CollectionUtils.isEmpty(listone)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_TASK_NOT_EXIST, "未查询当前患者信息！"));
		}
		return listone;
	}

	// 校验当前患者是否有推送信息
	private boolean checkExise(String userId) throws Exception {
		String argmsg = "";// 调用医院接口返回的信息
		boolean flag = false;
		Map<String, Object> mapInfo = new HashMap<String, Object>();
		Date date = new Date();
		String dateTime = DateUtil.getDate_8(date);
		mapInfo.put("bak1", dateTime);
		mapInfo.put("bak2", Constants.STRING_SERVICECODE_A09U004O);
		Map<String, Object> mapOut = patientDao.selectoutTableInfo(mapInfo);
		if (mapOut != null && mapOut.size() > 0) {
			argmsg = (String) mapOut.get("template");
		} else {
			dateTime = DateUtil.calcDay2(dateTime, "-", 1);
			mapInfo.put("bak1", dateTime);
			mapOut = patientDao.selectoutTableInfo(mapInfo);
			if (mapOut != null && mapOut.size() > 0) {
				argmsg = (String) mapOut.get("template");
			} else {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_TASK_NOT_EXIST, "当前没有推送患者！"));
			}
		}

		if (!StringUtils.isEmpty(argmsg)) {
			List<Map<String, Object>> listone = ToolUtils.FormatXml(argmsg);
			logger.info("转化后的list：" + listone.toString());
			for (int i = 0; i < listone.size(); i++) {
				Map<String, Object> map = listone.get(i);
				if (map.containsValue(userId)) {
					flag = true;
					break;
				}
			}
		}
		return flag;
	}

	@Override
	@Transactional
	public int checkVerifyCodeLh(String phoneNo, String verifyCode, String smsType, String type, String wechat_id)
			throws Exception {
		int flag = 1;
		String currTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 创建时间
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("openId", wechat_id);
		map.put("phoneNo", phoneNo);
		List<Map<String, Object>> list = null;
		if (!StringUtils.isEmpty(wechat_id) && !"null".equals(wechat_id)) {
			list = IConfCacheDAO.selectwechat(map);
		}
		map.put("verifyCode", verifyCode);
		map.put("smsType", smsType);
		map.put("minute", 10);
		// 对验证码验证
		logger.info("sssssssss: " + map.toString());
		List<Map<String, Object>> lists = IPtSmsRdDao.selectVerifyCode(map);
		if (lists.size() > 0) {
			flag = 0;
			// 将短信验证码置为已校验
			map.put("verifyStatus", "02");
			IPtSmsRdDao.updateSms(map);
			if (list == null || list.size() <= 0) {
				map.put("wechat_id", wechat_id);
				map.put("id", updateAccept);
				map.put("createTime", currTime);
				map.put("remark", "手机微信绑定");
				map.put("bak1", "lovely");
				map.put("bak2", "");
				map.put("bak3", "");
				IConfCacheDAO.savwechatInfo(map);
			} else {
				IConfCacheDAO.updatewechat(map);
			}
			return flag;
		} else {
			// 将短信验证码置为已校验
			map.remove("verifyCode");
			List<Map<String, Object>> listone = IPtSmsRdDao.selectVerifyCode(map);
			if (listone != null && listone.size() > 0) {
				String verify_code = listone.get(0).get("verify_code").toString();
				Jedis jedis = null;
				try {
					jedis = jedisPool.getResource();
					String code = jedis.get(verify_code);
					int inter = 0;
					if (code == null) {
						jedis.set(verify_code, "1");
					} else {
						inter = Integer.parseInt(code);
					}
					logger.info("inter~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + inter);
					if (inter == 5) {
						jedis.del(verify_code);
						map.put("minute", 1440);
						map.put("verifyStatus", "03");
						IPtSmsRdDao.updateSms(map);
						logger.info("111111111" + map.toString());
						return flag;
					} else {
						String str = inter + 1 + "";
						jedis.set(verify_code, str);
						throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
								"尊敬的用户，您的验证码输入错误，请核对!"));
					}

				} catch (JedisConnectionException jex) {
					logger.error("redis连接异常..." + jex.getMessage());
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
				} finally {
					if (null != jedis) {
						try {
							jedis.close();
							logger.warn("close redis connection...");
						} catch (Exception ex) {
							ex.printStackTrace();
							throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
									"Redis缓存关闭失败!"));
						}
					}
				}
			} else {
				throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
						"尊敬的用户，您的验证码已经失效，请重新获取!"));
			}
		}
	}

	// 通过微信或者是服务号码和租户查询用户列表
	@Override
	public Map<String, Object> queryUserMassage(Map<String, Object> paramMap) throws Exception {
		logger.info("queryUserMassage : " + paramMap.toString());
		Map<String, Object> map = new HashMap<String, Object>();
		String phoneNum = (String) paramMap.get("phoneNo");
		String tenantId = (String) paramMap.get("tenantId");
		String queueId = (String) paramMap.get("queueId");
		// 先根据微信号 租户下是否建过用户
		Map<String, Object> qryPtMap = new HashMap<String, Object>();
		qryPtMap.put("phoneNo", phoneNum);
		qryPtMap.put("tenantId", tenantId);
		qryPtMap.put("userName", (String) paramMap.get("userName"));
		qryPtMap.put("userType", (String) paramMap.get("userType"));
		List<Patient> ptList = patientDao.selectByPhoneNo(qryPtMap);

		String userId = "";
		// 根据科室ID 查询租户ID
		Map<String, Object> ptMap = new HashMap<String, Object>();
		if (!CollectionUtils.isEmpty(ptList)) {
			userId = ptList.get(0).getId();
		} else {
			map.put("user", "N");// 没有用户
			map.put("SDS2", "N");// 抑郁
			map.put("SAS2", "N");// 焦虑
			return map;
		}
		ptMap.put("userId", userId);
		ptMap.put("tenantId", tenantId);
		ptMap.put("queueId", queueId);
		List<String> statulist = new ArrayList<String>();
		statulist.add(Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
		ptMap.put("status", statulist);
		Map<String, Object> MapIn = new HashMap<String, Object>();
		List<PatientQueueScheme> queueSchemeList = patientQueueSchemeDao.selectByUserId(ptMap);
		String ptSchemeId = "";
		if (CollectionUtils.isEmpty(queueSchemeList)) {
			map.put("user", "N");// 没有用户
			map.put("SDS2", "N");// 抑郁
			map.put("SAS2", "N");// 焦虑
			return map;
		} else {
			map.put("user", "Y");// 没有用户
			List<String> typeList = new ArrayList<String>();
			typeList.add(Constants.FOLLOW_EVALUATION_PREGNANT_SDS2);
			MapIn.put("userId", userId);
			MapIn.put("typeList", typeList);
			MapIn.put("tenantId", tenantId);
			int total = followEvaluationService.selectPtEvaluationResultCount(MapIn);
			if (total > 0) {
				map.put("SDS2", "Y");// 抑郁
			} else {
				map.put("SDS2", "N");// 抑郁
			}
			typeList.clear();
			typeList.add(Constants.FOLLOW_EVALUATION_PREGNANT_SAS2);
			MapIn.put("typeList", typeList);
			total = followEvaluationService.selectPtEvaluationResultCount(MapIn);
			if (total > 0) {
				map.put("SAS2", "Y");// 焦虑
			} else {
				map.put("SAS2", "N");// 焦虑
			}
		}
		// 更新建档信息
		ptSchemeId = queueSchemeList.get(0).getId();
		ptMap.clear();
		ptMap.put("seqNo", Constants.TASK_SEQ_FOR_INIT);
		ptMap.put("ptSchemeId", ptSchemeId);
		// 查询taskid
		List<PatientTask> taskList = patientTaskDao.select(ptMap);
		String taskId = "";
		if (!CollectionUtils.isEmpty(taskList)) {
			taskId = taskList.get(0).getId();
		}
		MapIn.put("taskId", taskId);
		List<Object> conDataList = new ArrayList<Object>();
		List<Object> contentIdList = new ArrayList<Object>();
		List<PatientTaskContent> ptcList = patientTaskConDao.selectContentByTaskId(MapIn);
		if (!CollectionUtils.isEmpty(ptcList)) {
			// questiones
			int ipt = 0;
			int isize = ptcList.size();
			Map<String, Object> templMap = new HashMap<String, Object>();
			Map<String, Object> equalMap = new HashMap<String, Object>();
			// 找出模板内容相同的问卷
			for (ipt = 0; ipt < isize; ipt++) {
				PatientTaskContent ptaskc = ptcList.get(ipt);
				String templType = ptaskc.getTemplType();
				String templVersionId = ptaskc.getTemplVersionid();
				if (Constants.QUESTIONNAIRE_TYPE_0.equals(templType)) {
					templMap.put("id", templVersionId);
					List<ContentTemplVersion> ctvList = contentTemplDao.selectContentTemplNoTextById(templMap);
					if (null == ctvList || 0 == ctvList.size()) {
						continue;
					}
					String equalId = ctvList.get(0).getEqualId();
					if (!StringUtils.isEmpty(equalId)) {
						equalMap.put(equalId, templVersionId);
					}
				}
			}
			logger.warn("equalMap==" + equalMap.toString());

			// 剔除相同内容的非门诊问卷
			boolean eraseFlag = false;
			Map<String, Object> dataOut = new HashMap<String, Object>();
			Map<String, Object> contVerMap = new HashMap<String, Object>();
			for (ipt = 0; ipt < isize; ipt++) {
				PatientTaskContent ptaskc = ptcList.get(ipt);
				Map<String, Object> ptcInMap = new HashMap<String, Object>();
				String templType = ptaskc.getTemplType();
				String templVersionId = ptaskc.getTemplVersionid();
				if (!Constants.QUESTIONNAIRE_TYPE_0.equals(templType)) {
					if (null != equalMap.get(templVersionId)) {
						// 该问卷与门诊问卷内容相同，需要剔除
						logger.warn("erase templVersionId==" + templVersionId);
						eraseFlag = true;
						continue;
					}
				}
				ptcInMap.put("templType", templType);
				ptcInMap.put("contentId", ptaskc.getId());
				contentIdList.add(ptcInMap);

				// 获取内容模板
				contVerMap.clear();
				contVerMap.put("templVersionId", templVersionId);
				dataOut = patientService.getContTemplData(contVerMap);
				if (null != dataOut.get("contData")) {
					conDataList.add(dataOut.get("contData"));
				}
			}
			map.put("questiones", conDataList);

			// values
			HashMap<String, Object> questionMap = new HashMap<String, Object>();
			if (!eraseFlag) {
				// 没有重复问卷，优先查门诊答案，没有门诊答案，则查询所有答案
				Map<String, Object> valMapIn = new HashMap<String, Object>();
				valMapIn.put("taskId", taskId);
				valMapIn.put("contDataTemplType", Constants.QUESTIONNAIRE_TYPE_0);
				List<PatientContentData> ptTaskConList = patientTaskConDao.selectContentDataByTaskId(valMapIn);
				if (!CollectionUtils.isEmpty(ptTaskConList)) {
					int k = 0;
					for (; k < ptTaskConList.size(); k++) {
						PatientContentData pcdVo = ptTaskConList.get(k);
						questionMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
					}
				} else {
					valMapIn.put("contDataTemplType", null);
					ptTaskConList = patientTaskConDao.selectContentDataByTaskId(valMapIn);
					if (!CollectionUtils.isEmpty(ptTaskConList)) {
						int k = 0;
						for (; k < ptTaskConList.size(); k++) {
							PatientContentData pcdVo = ptTaskConList.get(k);
							questionMap.put(pcdVo.getQuestionId(), pcdVo.getQuestionAnswer());
						}
					}
				}
			}

			map.put("values", questionMap);
			map.put("ptSchemeId", ptSchemeId);
			map.put("userId", userId);
			map.put("taskId", taskId);
		}
		return map;

	}

	// 查询产妇和宝宝的绑定情况
	@Override
	public Map<String, Object> queryBaby(Map<String, Object> paramMap) throws Exception {
		logger.info("queryBaby : " + paramMap.toString());
		String motherName   =  (String) paramMap.get("motherName");
		String matertel   =  (String) paramMap.get("phoneNo");
		Map<String,Object> map = new HashMap<String,Object>();
		Map<String,Object> mapIn = new HashMap<String,Object>();
		List<Map<String,Object>> list  =  patientDao.selectPtSchemeAndPatientByPhoneAndQueueId(paramMap);
		if(!CollectionUtils.isEmpty(list)) {
			mapIn.put("userId", list.get(0).get("id"));
			mapIn.put("queueId", list.get(0).get("queueId"));
			//查询用户扩展信息
			List<PtUserextendInfo> ptuser = ptExtendDao.selectPtExtendInfo(mapIn);
			if(!CollectionUtils.isEmpty(ptuser)) {
				mapIn.clear();
				for(int i=0;i<ptuser.size();i++) {
					mapIn.put(ptuser.get(i).getParamName(), ptuser.get(i).getParamValue());
				}
			}else {
				mapIn = null;
			}
			map.put("user", "Y");
			map.put("userList", list);
		}else {
			map.put("user", "N");
		}

		String platform_key = "";
		if(StringUtils.isEmpty(mapIn.get("motherId"))) {
			platform_key = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_USERID);
		}else {
			platform_key = (String) mapIn.get("motherId");
		}

		if(!StringUtils.isEmpty(mapIn.get("motherName"))) {
			motherName = (String) mapIn.get("motherName");
		}

		//如果没有产妇识别码，那么调用医院的接口获得
		//if(StringUtils.isEmpty(mapIn.get("motherhash"))) {
			Map<String, Object> paramMap1 = new LinkedHashMap<String, Object>();
			paramMap1.put("motherName", motherName);
			paramMap1.put("mothertel", matertel);
			paramMap1.put("is_bind", "no");
			paramMap1.put("platform_code", Constants.SOURCE_TPLATFORM_CODE);
			paramMap1.put("platform_key", platform_key);
			paramMap1.put("code", Constants.STRING_SERVICECODE_A09U007O);
			String argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", paramMap1);
			//String argmsg = "";
			//argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row result=\"0\" message=\"未找到患者信息，请检查与预约时登记的信息是否一致\" mothername=\"**智\" motherhash=\"88888888\" is_bind=\"no\" /></rows>";
			logger.info("################" + argmsg);
			List<Map<String, Object>> lists = ToolUtils.FormatXml(argmsg);
			logger.info(lists.toString());
			if (lists == null || lists.size() <= 0) {
				//如果查不到任何信息则报错
				mapIn.put("motherflag", "N");
			}else {
				if(StringUtils.isEmpty(lists.get(0).get("motherhash"))) {
					mapIn.put("motherflag", "N");
				}else {
					mapIn.put("motherhash", lists.get(0).get("motherhash"));
					mapIn.put("motherflag", "Y");
				}
			}
		//}
		mapIn.put("motherId", platform_key);
		mapIn.put("motherName", motherName);
		map.put("userExtend", mapIn);
		return map;
	}

	// 解绑产妇和宝宝的关系
	@Override
	@Transactional
	public Map<String, Object> unbindWomenBaby(Map<String, Object> paramMap) throws Exception {
		logger.info("unbindWomenBaby : " + paramMap.toString());
		HashMap<String,Object> map = new HashMap<String,Object>(paramMap);
		Map<String,Object> mapIn = new LinkedHashMap<String,Object>(paramMap);
		Map<String, Object>  mapOut = new HashMap<String,Object>();
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
		mapIn.remove("queueId");
		mapIn.remove("userId");
		mapIn.put("is_bind", "unbind");
		mapIn.put("platform_code", Constants.SOURCE_TPLATFORM_CODE);
		mapIn.put("platform_key", paramMap.get("userId"));
		mapIn.put("code", Constants.STRING_SERVICECODE_A09U007O);
		String argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", mapIn);
		//String argmsg = "";
		//argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row result=\"0\" message=\"非本人不可解绑\" babyname=\"**2\" babyhash=\"18214889581\" is_bind=\"unbind\" /><row result=\"0\" message=\"解绑1条记录\" babyname=\"**2\" babyhash=\"18214889581\" is_bind=\"unbind\" /></rows>";
		logger.info("################" + argmsg);
		List<Map<String, Object>> lists = ToolUtils.FormatXml(argmsg);
		logger.info(lists.toString());
		if (lists == null || lists.size() <= 0) {
			//如果查不到任何信息则报错
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "未找到患者信息，请检查与预约时登记的信息是否一致"));
		}else {
				for(int i=0;i<lists.size();i++) {
					String message = (String) lists.get(i).get("message");
					if(!StringUtils.isEmpty(message)&&message.indexOf("解绑")!=-1 &&message.indexOf("记录")!=-1) {
						String index = message.substring(message.indexOf("绑")+1, message.indexOf("绑")+2);
						if(!StringUtils.isEmpty(index)) {
							int all = Integer.parseInt(index);
							if(all>0) {
								map.put("updateTime", updateTime);
								map.put("updateAccept", updateAccept);
								map.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
								map.put("platform_key", paramMap.get("userId"));
								map.put("babyhash", "");
								map.put("isSuccess", "");
								map.put("message", "");
								patientQueueSchemeDao.updateBabyBindByuserId(map);
								patientqueryCardDAO.PatientQueueSchemeHis(map);
								return mapOut;
							}
						}
					}else if(!StringUtils.isEmpty(message)&&message.indexOf("已解绑")!=-1){
						map.put("updateTime", updateTime);
						map.put("updateAccept", updateAccept);
						map.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
						map.put("platform_key", paramMap.get("userId"));
						map.put("babyhash", "");
						map.put("isSuccess", "");
						map.put("message", "");
						patientQueueSchemeDao.updateBabyBindByuserId(map);
						patientqueryCardDAO.PatientQueueSchemeHis(map);
						return mapOut;
					}
				}
		}
		throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, (String) lists.get(0).get("message")));
	}


	// 绑定产妇和宝宝的关系
	@Override
	@Transactional
	public Map<String, Object> bindWomenBaby(Map<String, Object> paramMap) throws Exception {
		logger.info("bindWomenBaby : " + paramMap.toString());
		HashMap<String,Object> map = new HashMap<String,Object>(paramMap);
		Map<String,Object> mapIn = new LinkedHashMap<String,Object>(paramMap);
		Map<String, Object>  mapOut = new HashMap<String,Object>();
		String updateAccept = SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID);// 操作流水
		String updateTime = DateUtil.getTimeString(DateUtil.getSysDateA());// 当前时间
		mapIn.remove("queueId");
		mapIn.remove("userId");
		mapIn.put("babyName", paramMap.get("babyName"));
		mapIn.put("babyidcard", paramMap.get("babyidcard"));
		mapIn.put("motherhash", paramMap.get("motherhash"));
		mapIn.put("is_bind", "bind");
		mapIn.put("platform_code", Constants.SOURCE_TPLATFORM_CODE);
		mapIn.put("platform_key", paramMap.get("userId"));
		mapIn.put("code", Constants.STRING_SERVICECODE_A09U007O);
		String argmsg = bizInterClient.call(Constants.SERVICE_NAME_FOR_SERVICE, "", mapIn);
		//String argmsg = "";
		//argmsg = "<?xml version=\"1.0\" encoding=\"gbk\"?><rows><row result=\"0\" message=\"未找到患者信息，请检查与预约时登记的信息是否一致\" mothername=\"**智\" babyhash=\"123456789\" is_bind=\"no\" /></rows>";
		logger.info("################" + argmsg);
		List<Map<String, Object>> lists = ToolUtils.FormatXml(argmsg);
		logger.info(lists.toString());
		if (lists == null || lists.size() <= 0) {
			//如果查不到任何信息则报错
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, paramMap.get("babyName").toString()+"没有绑定成功！"));
		}else {
				if(StringUtils.isEmpty(lists.get(0).get("babyhash"))) {
					String Message = "";
					if(StringUtils.isEmpty(lists.get(0).get("message"))) {
						 Message = paramMap.get("babyName").toString()+"没有绑定成功！";
					}else {
						 Message = (String) lists.get(0).get("message");
					}
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, Message));
				}else {
					map.put("updateTime", updateTime);
					map.put("updateAccept", updateAccept);
					map.put("updateType", Constants.UPDATE_TYPE_UPDATE_U);
					map.put("platform_key", paramMap.get("userId"));
					map.put("babyhash", lists.get(0).get("babyhash"));
					map.put("isSuccess", "");
					map.put("message", "");
					System.out.println();
					patientQueueSchemeDao.updateBabyBindByuserId(map);
					patientqueryCardDAO.PatientQueueSchemeHis(map);
					mapOut.put("flag", true);
					mapOut.put("babyhash", lists.get(0).get("babyhash"));
				}
		}
		return mapOut;

	}

	// 绑定产妇和宝宝的关系
	@Override
	@Transactional
	public Map<String, Object> getPatientAddQuestion(Map<String, Object> paramMap) throws Exception {
		logger.info("getPatientAddQuestion : " + paramMap.toString());
		Map<String,Object> retMap = new LinkedHashMap<String,Object>();
		//查询对队列信息
		List<FollowQueue> queueList = queueDao.selectById(paramMap);
		if(CollectionUtils.isEmpty(queueList)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "队列信息不存在"));
		}
		FollowQueue  queue  = queueList.get(0);
		paramMap.put("schemeId", queue.getSchemeId());
	    paramMap.put("queueId", paramMap.get("id"));
	    retMap = followQueueSerivce.qryQueueSchemePatientAddContent(paramMap);
		return retMap;

	}

		// 科研id查询用户是否存在
		@Override
		public Map<String, Object> queryUserByScientific(HashMap<String, Object> qryPqsMap) throws Exception {
			logger.info("queryUserByScientific()~~~~~~~~：" + qryPqsMap.toString());
			Map<String, Object> map = new HashMap<String, Object>();
			String queueId = (String) qryPqsMap.get("queueId");
			String userName = (String) qryPqsMap.get("userName");
			String phoneNo = (String) qryPqsMap.get("phoneNo");
			String ScientificId = (String) qryPqsMap.get("ScientificId");
			String tenantId = (String) qryPqsMap.get("tenantId");
			map.put("queueId",queueId);
			map.put("ScientificId",ScientificId);
			map.put("tenantId",tenantId);
			map.put("userStatus",Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
			map.put("questionId", Constants.QUESTION_ID_FOR_RESEARCH_ID);
			map.put("questionAnswer", ScientificId.toUpperCase());
			//如果是单独的科研id，直接查询答案表，然后判断用户是否存在
			if(StringUtils.isEmpty(phoneNo)&&!StringUtils.isEmpty(ScientificId)) {
				int count = patientTaskConDao.selectQustionAnswer(map);
				if(count>0) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, ScientificId+":当前科研编号已经存在!"));
				}
			}else {
			//如果是用户姓名+号码+科研id，关联查询
				map.put("userName",userName);
				map.put("phoneNo",phoneNo);
				int count = patientTaskConDao.selectQustionAnswer(map);
				if(count>0) {
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "该患者已经加入当前队列！"));
				}
			}
			Map<String, Object> mapOut = new HashMap<String, Object>();
			return mapOut;
		}

}

